Mastering Data Analysis with Pandas

Pandas is useful when the work needs a clear sequence: inspect the input, clean the awkward parts, reshape it for the question at hand, and only then visualize the result. This guide collects those steps in one place.

Getting Started with Pandas

Installation and Import

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Set display options
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)

Creating DataFrames

# From dictionary
data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'Diana'],
    'Age': [25, 30, 35, 28],
    'City': ['New York', 'London', 'Tokyo', 'Paris'],
    'Salary': [50000, 60000, 70000, 55000]
}
df = pd.DataFrame(data)

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

# From Excel file
df = pd.read_excel('data.xlsx', sheet_name='Sheet1')

Data Exploration

Basic Information

# Basic info
print(df.info())
print(df.describe())
print(df.head())
print(df.tail())

# Data types
print(df.dtypes)

# Missing values
print(df.isnull().sum())

# Unique values
print(df['City'].unique())
print(df['City'].value_counts())

Data Shape and Structure

# Shape
print(f"Rows: {df.shape[0]}, Columns: {df.shape[1]}")

# Column names
print(df.columns.tolist())

# Index information
print(df.index)

Data Cleaning

Handling Missing Values

# Check for missing values
missing_data = df.isnull().sum()
print(missing_data)

# Drop rows with any missing values
df_clean = df.dropna()

# Drop rows with all missing values
df_clean = df.dropna(how='all')

# Fill missing values
df['Age'] = df['Age'].fillna(df['Age'].mean())
df['City'] = df['City'].fillna('Unknown')

# Forward fill
df['Salary'] = df['Salary'].ffill()

# Backward fill
df['Salary'] = df['Salary'].bfill()

Data Type Conversion

# Convert to numeric
df['Age'] = pd.to_numeric(df['Age'], errors='coerce')

# Convert to datetime
df['Date'] = pd.to_datetime(df['Date'])

# Convert to category
df['City'] = df['City'].astype('category')

# Convert to string
df['ID'] = df['ID'].astype(str)

Removing Duplicates

# Check for duplicates
print(df.duplicated().sum())

# Remove duplicates
df_unique = df.drop_duplicates()

# Remove duplicates based on specific columns
df_unique = df.drop_duplicates(subset=['Name', 'Email'])

Data Selection and Filtering

Basic Selection

# Select columns
df[['Name', 'Age']]
df.loc[:, ['Name', 'Age']]

# Select rows
df.iloc[0:5]  # First 5 rows
df.iloc[0:5, 0:3]  # First 5 rows, first 3 columns

# Boolean indexing
df[df['Age'] > 30]
df[(df['Age'] > 30) & (df['Salary'] > 60000)]

Advanced Filtering

# Multiple conditions
filtered_df = df[
    (df['Age'] >= 25) &
    (df['Age'] <= 35) &
    (df['City'].isin(['New York', 'London']))
]

# String operations
df[df['Name'].str.contains('John')]
df[df['Name'].str.startswith('A')]
df[df['Email'].str.endswith('.com')]

# Regular expressions
df[df['Name'].str.match(r'^[A-Z][a-z]+$')]

Data Transformation

Adding New Columns

# Simple calculation
df['Age_Group'] = df['Age'].apply(lambda x: 'Young' if x < 30 else 'Old')

# Using apply with function
def categorize_salary(salary):
    if salary < 50000:
        return 'Low'
    elif salary < 70000:
        return 'Medium'
    else:
        return 'High'

df['Salary_Category'] = df['Salary'].apply(categorize_salary)

# Using np.where
df['Bonus'] = np.where(df['Salary'] > 60000, df['Salary'] * 0.1, 0)

# Using np.select for multiple conditions
conditions = [
    df['Age'] < 25,
    (df['Age'] >= 25) & (df['Age'] < 35),
    df['Age'] >= 35
]
choices = ['Junior', 'Mid', 'Senior']
df['Level'] = np.select(conditions, choices, default='Unknown')

Grouping and Aggregation

# Basic grouping
grouped = df.groupby('City')
print(grouped['Salary'].mean())
print(grouped['Age'].std())

# Multiple aggregations
agg_results = df.groupby('City').agg({
    'Salary': ['mean', 'median', 'std'],
    'Age': ['min', 'max', 'count']
})

# Custom aggregation
def salary_range(group):
    return group.max() - group.min()

df.groupby('City')['Salary'].apply(salary_range)

Data Visualization

Basic Plotting

# Line plot
df.plot(x='Date', y='Sales', kind='line')

# Bar plot
df['City'].value_counts().plot(kind='bar')

# Histogram
df['Age'].hist(bins=20)

# Scatter plot
df.plot(x='Age', y='Salary', kind='scatter')

Advanced Visualization

# Using matplotlib
plt.figure(figsize=(10, 6))
plt.subplot(2, 2, 1)
df['Age'].hist(bins=20)
plt.title('Age Distribution')

plt.subplot(2, 2, 2)
df['Salary'].plot(kind='box')
plt.title('Salary Distribution')

plt.subplot(2, 2, 3)
df.groupby('City')['Salary'].mean().plot(kind='bar')
plt.title('Average Salary by City')

plt.subplot(2, 2, 4)
df.plot(x='Age', y='Salary', kind='scatter')
plt.title('Age vs Salary')

plt.tight_layout()
plt.show()

# Using seaborn
sns.pairplot(df[['Age', 'Salary', 'City']], hue='City')
sns.heatmap(df.corr(), annot=True, cmap='coolwarm')

Time Series Analysis

Working with Dates

# Convert to datetime
df['Date'] = pd.to_datetime(df['Date'])

# Set as index
df.set_index('Date', inplace=True)

# Resampling
daily_sales = df['Sales'].resample('D').sum()
monthly_avg = df['Sales'].resample('M').mean()

# Rolling windows
df['Sales_MA_7'] = df['Sales'].rolling(window=7).mean()
df['Sales_MA_30'] = df['Sales'].rolling(window=30).mean()

# Time-based filtering
df_2023 = df[df.index.year == 2023]
df_q1 = df[df.index.quarter == 1]

Time Series Visualization

# Plot time series
df['Sales'].plot(figsize=(12, 6))
plt.title('Sales Over Time')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.show()

# Plot with moving averages
df[['Sales', 'Sales_MA_7', 'Sales_MA_30']].plot(figsize=(12, 6))
plt.title('Sales with Moving Averages')
plt.show()

Advanced Techniques

Pivot Tables

# Create pivot table
pivot = df.pivot_table(
    values='Sales',
    index='City',
    columns='Month',
    aggfunc='sum',
    fill_value=0
)

# Multi-level pivot
pivot_multi = df.pivot_table(
    values=['Sales', 'Profit'],
    index=['City', 'Product'],
    columns='Quarter',
    aggfunc={'Sales': 'sum', 'Profit': 'mean'}
)

Merging DataFrames

# Inner join
merged = pd.merge(df1, df2, on='ID', how='inner')

# Left join
merged = pd.merge(df1, df2, on='ID', how='left')

# Outer join
merged = pd.merge(df1, df2, on='ID', how='outer')

# Concatenate DataFrames
combined = pd.concat([df1, df2], ignore_index=True)

Performance Optimization

# Use vectorized operations
df['New_Column'] = df['Column1'] * df['Column2']  # Fast

# Avoid apply when possible
df['Category'] = df['Value'].apply(lambda x: 'High' if x > 100 else 'Low')  # Slow
df['Category'] = np.where(df['Value'] > 100, 'High', 'Low')  # Fast

# Use categorical data types
df['City'] = df['City'].astype('category')  # Memory efficient

# Use query for complex filtering
df.query('Age > 30 and Salary < 70000')

Best Practices

Code Organization

# Use functions for repetitive tasks
def clean_data(df):
    """Clean and preprocess the dataframe"""
    df = df.dropna()
    df = df.drop_duplicates()
    df['Date'] = pd.to_datetime(df['Date'])
    return df

def analyze_sales(df):
    """Analyze sales data"""
    summary = df.groupby('City').agg({
        'Sales': ['sum', 'mean', 'count'],
        'Profit': 'mean'
    })
    return summary

# Use context managers for file operations
with pd.ExcelWriter('analysis_results.xlsx') as writer:
    df.to_excel(writer, sheet_name='Raw Data')
    summary.to_excel(writer, sheet_name='Summary')

Error Handling

try:
    df = pd.read_csv('data.csv')
    df = clean_data(df)
    results = analyze_sales(df)
    print("Analysis completed successfully!")
except FileNotFoundError:
    print("Data file not found!")
except pd.errors.EmptyDataError:
    print("Data file is empty!")
except Exception as e:
    print(f"An error occurred: {e}")

Conclusion

Pandas is an incredibly powerful tool for data analysis. The key to mastering it is practice and understanding when to use different techniques. Start with basic operations and gradually move to more advanced features.

Resources


Data analysis is not just about tools, but about asking the right questions and finding meaningful insights.