Tuesday, 21 October 2025

#2 Pandas - Basics

๐Ÿผ Pandas Concepts with Demo Programs

This post covers essential Pandas concepts every data enthusiast should know — from creating DataFrames to filtering, grouping, and merging data. Each example includes syntax highlighting and a handy copy button!


1️⃣ Importing Pandas & Creating DataFrame


import pandas as pd

# Create a simple DataFrame
data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'David'],
    'Age': [25, 30, 35, 40],
    'City': ['Chennai', 'Bangalore', 'Delhi', 'Mumbai']
}

df = pd.DataFrame(data)
print(df)
df.to_csv('data.csv',index=False) # for next ex
2️⃣ Reading Data from CSV

# Read CSV file
df = pd.read_csv('data.csv')

# Display first 5 rows
print(df.head())

3️⃣ Data Selection — iloc & loc


# Select by row and column index
print(df.iloc[0, 1])

# Select by label
print(df.loc[0, 'Name'])

4️⃣ Filtering Rows


# Filter rows where Age > 30
filtered = df[df['Age'] > 30]
print(filtered)

5️⃣ GroupBy and Aggregations


# Group by City and get average Age
grouped = df.groupby('City')['Age'].mean()
print(grouped)

6️⃣ Sorting & Renaming Columns


# Sort by Age descending
df_sorted = df.sort_values(by='Age', ascending=False)
print(df_sorted)

# Rename column
df_renamed = df.rename(columns={'City': 'Location'})
print(df_renamed)

7️⃣ Handling Missing Data


# Fill missing values
df.fillna({'Age': df['Age'].mean()}, inplace=True)

# Drop rows with NaN
df.dropna(inplace=True)

8️⃣ Merging & Joining DataFrames


# Merge two DataFrames on 'Name'
df1 = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Score': [85, 90]})
df2 = pd.DataFrame({'Name': ['Bob', 'Charlie'], 'Rank': [2, 3]})

merged = pd.merge(df1, df2, on='Name', how='outer')
print(merged)

9️⃣ Pivot Tables


# Create a pivot table
pivot = pd.pivot_table(df, values='Age', index='City', aggfunc='mean')
print(pivot)

๐Ÿ”Ÿ Exporting Data


# Export DataFrame to CSV
df.to_csv('output.csv', index=False)
print("✅ Data exported successfully!")

๐Ÿ’ก Tip: Pandas + NumPy + Matplotlib = a powerful combo for Data Science beginners!

Please also refer Cook Book

No comments:

Post a Comment

#21a Dunder Method - Samples

Python Dunder (Magic) Methods – Complete Guide with Demos Python Dunder (Magic) Methods – Complete Guide with Demos ...