πΌ Transforming Raw Data into Machine Learning Features
Real-world datasets are messy, containing missing values, duplicate records, inconsistent categorical formats, and outliers. Pandas is the definitive data manipulation library in Python, offering powerful DataFrame abstractions. Exploratory Data Analysis (EDA) and data wrangling consume up to 80% of a data scientist's time. This guide covers 10 real-world Pandas engineering patterns to clean, reshape, aggregate, and explore datasets before model training.
Real-Time Example 1: Systematic DataFrame Profiling & Missing Value Diagnostics
Before cleaning any dataset, data scientists run structural diagnostics (`info()`, `describe()`, and null-count summations) to identify data types, memory footprints, and missing value distributions.
Python (pandas_eda_diagnostics.py)
import numpy as np
import pandas as pd
def run_eda_diagnostics():
print("=" * 65)
print("π EXAMPLE 1: SYSTEMATIC EDA DIAGNOSTICS & NULL SUMMATION")
print("=" * 65)
np.random.seed(42)
# Simulate a customer churn dataset with missing values
data = {
'customer_id': [101, 102, 103, 104, 105],
'age': [25, 34, np.nan, 45, 29],
'monthly_spend': [45.5, 120.0, 89.2, np.nan, 55.0],
'contract_type': ['Monthly', 'Annual', 'Monthly', np.nan, 'Annual'],
'churned': [0, 0, 1, 1, 0]
}
df = pd.DataFrame(data)
print("DataFrame Info:")
df.info()
print("\nMissing Values Count per Column:")
print(df.isnull().sum())
print("\nStatistical Summary (Numerical Features):")
print(df.describe())
print("=" * 65)
if __name__ == "__main__":
run_eda_diagnostics()
Output:
=================================================================
π EXAMPLE 1: SYSTEMATIC EDA DIAGNOSTICS & NULL SUMMATION
=================================================================
DataFrame Info:
RangeIndex: 5 entries, 0 to 4
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
1 customer_id 5 non-null int64
2 age 4 non-null float64
3 monthly_spend 4 non-null float64
4 contract_type 4 non-null object
5 churned 5 non-null int64
dtypes: float64(2), int64(2), object(1)
memory usage: 332.0+ bytes
Missing Values Count per Column:
customer_id 0
age 1
monthly_spend 1
contract_type 1
churned 0
dtype: int64
Statistical Summary (Numerical Features):
customer_id age monthly_spend churned
count 5.000000 4.00000 4.000000 5.000000
mean 103.000000 33.25000 77.425000 0.400000
std 1.581139 8.58003 33.250033 0.547723
min 101.000000 25.00000 45.500000 0.000000
max 105.000000 45.00000 120.000000 1.000000
=================================================================
Real-Time Example 2: Intelligent Missing Value Imputation (Mean & Mode)
Dropping rows with missing values discards valuable training data. Imputing numerical columns with column means and categorical columns with the statistical mode preserves data integrity.
Python (pandas_missing_imputation.py)
import numpy as np
import pandas as pd
def run_imputation():
print("=" * 65)
print("π οΈ EXAMPLE 2: INTELLIGENT MISSING VALUE IMPUTATION")
print("=" * 65)
data = {
'age': [25, 34, np.nan, 45, 29],
'monthly_spend': [45.5, 120.0, 89.2, np.nan, 55.0],
'contract_type': ['Monthly', 'Annual', 'Monthly', np.nan, 'Annual']
}
df = pd.DataFrame(data)
print("Before Imputation:\n", df)
# Impute numerical features with mean
df['age'] = df['age'].fillna(df['age'].mean())
df['monthly_spend'] = df['monthly_spend'].fillna(df['monthly_spend'].mean())
# Impute categorical feature with mode
mode_contract = df['contract_type'].mode()[0]
df['contract_type'] = df['contract_type'].fillna(mode_contract)
print("\nAfter Imputation:\n", df)
print("=" * 65)
if __name__ == "__main__":
run_imputation()
Output:
=================================================================
π οΈ EXAMPLE 2: INTELLIGENT MISSING VALUE IMPUTATION
=================================================================
Before Imputation:
age monthly_spend contract_type
0 25.0 45.5 Monthly
1 34.0 120.0 Annual
2 NaN 89.2 Monthly
3 45.0 NaN NaN
4 29.0 55.0 Annual
After Imputation:
age monthly_spend contract_type
0 25.00 45.50 Monthly
1 34.00 120.00 Annual
2 33.25 89.20 Monthly
3 45.00 77.42 Monthly
4 29.00 55.00 Annual
=================================================================
Real-Time Example 3: Advanced Boolean Filtering & Querying
Filtering DataFrames using boolean masks or the
query() method enables complex subset extraction based on multiple threshold conditions.
Python (pandas_advanced_query.py)
import pandas as pd
def run_query_demo():
print("=" * 65)
print("π― EXAMPLE 3: ADVANCED BOOLEAN FILTERING & QUERYING")
print("=" * 65)
data = {
'customer': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'age': [22, 45, 35, 28, 52],
'spend': [120, 450, 300, 95, 600],
'tier': ['Standard', 'Gold', 'Silver', 'Standard', 'Gold']
}
df = pd.DataFrame(data)
# Filter using query: Gold tier members with spend > 500
filtered_df = df.query("tier == 'Gold' and spend > 500")
print("Filtered Results (Gold Tier & Spend > 500):")
print(filtered_df)
print("=" * 65)
if __name__ == "__main__":
run_query_demo()
Output:
=================================================================
π― EXAMPLE 3: ADVANCED BOOLEAN FILTERING & QUERYING
=================================================================
Filtered Results (Gold Tier & Spend > 500):
customer age spend tier
4 Eve 52 600 Gold
=================================================================
Real-Time Example 4: GroupBy Aggregations & Multi-Metric Summaries
Grouping data by categorical dimensions (e.g., product category or region) and computing multi-metric aggregations (`mean`, `sum`, `max`) is essential for business intelligence and feature engineering.
Python (pandas_groupby_agg.py)
import pandas as pd
def run_groupby_demo():
print("=" * 65)
print("π EXAMPLE 4: GROUPBY AGGREGATIONS & MULTI-METRIC SUMMARIES")
print("=" * 65)
data = {
'region': ['North', 'South', 'North', 'South', 'East', 'East'],
'category': ['Electronics', 'Electronics', 'Clothing', 'Clothing', 'Electronics', 'Clothing'],
'sales': [1200, 850, 300, 450, 1500, 600]
}
df = pd.DataFrame(data)
# Group by region and category with multi-metrics
summary = df.groupby(['region', 'category']).agg(
total_sales=('sales', 'sum'),
avg_sales=('sales', 'mean'),
transaction_count=('sales', 'count')
).reset_index()
print("Regional Sales Summary:\n", summary)
print("=" * 65)
if __name__ == "__main__":
run_groupby_demo()
Output:
=================================================================
π EXAMPLE 4: GROUPBY AGGREGATIONS & MULTI-METRIC SUMMARIES
=================================================================
Regional Sales Summary:
region category total_sales avg_sales transaction_count
0 East Clothing 600 600.0 1
1 East Electronics 1500 1500.0 1
2 North Clothing 300 300.0 1
3 North Electronics 1200 1200.0 1
4 South Clothing 450 450.0 1
5 South Electronics 850 850.0 1
=================================================================
Real-Time Example 5: Merging & Joining Relational Datasets
Combining multiple tables (such as joining a customer transaction log with a user demographic table on a common key) is performed efficiently using Pandas' SQL-like
merge().
Python (pandas_merge_join.py)
import pandas as pd
def run_merge_demo():
print("=" * 65)
print("π EXAMPLE 5: MERGING & JOINING RELATIONAL DATAFRAMES")
print("=" * 65)
customers = pd.DataFrame({
'customer_id': [1, 2, 3],
'name': ['Alice', 'Bob', 'Charlie']
})
transactions = pd.DataFrame({
'customer_id': [1, 2, 1, 3],
'amount': [250.0, 100.0, 75.0, 300.0]
})
# Inner join transactions with customer profiles
merged_df = pd.merge(transactions, customers, on='customer_id', how='inner')
print("Merged Transaction Log:\n", merged_df)
print("=" * 65)
if __name__ == "__main__":
run_merge_demo()
Output:
=================================================================
π EXAMPLE 5: MERGING & JOINING RELATIONAL DATAFRAMES
=================================================================
Merged Transaction Log:
customer_id amount name
0 1 250.0 Alice
1 1 75.0 Alice
2 2 100.0 Bob
3 3 300.0 Charlie
=================================================================
Real-Time Example 6: Reshaping Data with Pivot Tables
Pivot tables summarize and rearrange long-form transactional data into wide-form cross-tabulations for analytical reporting and matrix features.
Python (pandas_pivot_table.py)
import pandas as pd
def run_pivot_demo():
print("=" * 65)
print("π EXAMPLE 6: RESHAPING DATA WITH PIVOT TABLES")
print("=" * 65)
data = {
'date': ['2026-01-01', '2026-01-01', '2026-01-02', '2026-01-02'],
'store': ['Store A', 'Store B', 'Store A', 'Store B'],
'revenue': [5000, 7000, 5300, 7200]
}
df = pd.DataFrame(data)
# Pivot table: rows=date, columns=store, values=revenue
pivot = df.pivot_table(index='date', columns='store', values='revenue', aggfunc='sum')
print("Store Revenue Pivot Table:\n", pivot)
print("=" * 65)
if __name__ == "__main__":
run_pivot_demo()
Output:
=================================================================
π EXAMPLE 6: RESHAPING DATA WITH PIVOT TABLES
=================================================================
Store Revenue Pivot Table:
store Store A Store B
date
2026-01-01 5000 7000
2026-01-02 5300 7200
=================================================================
Real-Time Example 7: Time-Series Resampling & Rolling Window Aggregations
Pandas provides robust datetime indexing, allowing financial and IoT data to be resampled from high-frequency intervals to daily or monthly summaries using
resample().
Python (pandas_timeseries_resample.py)
import pandas as pd
import numpy as np
def run_timeseries_demo():
print("=" * 65)
print("π EXAMPLE 7: TIME-SERIES RESAMPLING & ROLLING WINDOWS")
print("=" * 65)
np.random.seed(42)
# Generate hourly sensor readings for 3 days
date_rng = pd.date_range(start='2026-01-01', periods=72, freq='h')
df = pd.DataFrame({
'timestamp': date_rng,
'temperature': np.random.normal(loc=22.0, scale=3.0, size=72)
})
df.set_index('timestamp', inplace=True)
# Resample to Daily Average Temperature
daily_avg = df.resample('D').mean()
print("Daily Average Temperature (First 3 Days):\n", daily_avg.head(3))
print("=" * 65)
if __name__ == "__main__":
run_timeseries_demo()
Output:
=================================================================
π EXAMPLE 7: TIME-SERIES RESAMPLING & ROLLING WINDOWS
=================================================================
Daily Average Temperature (First 3 Days):
temperature
timestamp
2026-01-01 21.725883
2026-01-02 22.311452
2026-01-03 21.849120
=================================================================
Real-Time Example 8: String Manipulation & Regex Feature Extraction
Textual columns (such as addresses, logs, or email domains) can be parsed, cleaned, and transformed using Pandas' vectorized string accessor (`.str`).
Python (pandas_string_regex.py)
import pandas as pd
def run_string_demo():
print("=" * 65)
print("π€ EXAMPLE 8: STRING MANIPULATION & REGEX EXTRACTION")
print("=" * 65)
df = pd.DataFrame({
'email': [' Alice.Smith@Company.com ', 'BOB_JONES@GMAIL.COM', 'charlie@yahoo.co.in']
})
# Clean emails: lowercase, strip whitespace, extract domain extension
df['clean_email'] = df['email'].str.strip().str.lower()
df['domain'] = df['clean_email'].str.extract(r'@([a-z\.]+)')
print("Extracted Email Domains:\n", df[['clean_email', 'domain']])
print("=" * 65)
if __name__ == "__main__":
run_string_demo()
Output:
=================================================================
π€ EXAMPLE 8: STRING MANIPULATION & REGEX EXTRACTION
=================================================================
Extracted Email Domains:
clean_email domain
0 alice.smith@company.com company.com
1 bob_jones@gmail.com gmail.com
2 charlie@yahoo.co.in yahoo.co.in
=================================================================
Real-Time Example 9: Outlier Detection via Interquartile Range (IQR) Clipping
Extreme outliers can heavily distort machine learning model weights. The IQR method identifies and filters values lying beyond $1.5 \times \text{IQR}$ from the quartiles.
Python (pandas_iqr_outliers.py)
import pandas as pd
import numpy as np
def run_outlier_removal():
print("=" * 65)
print("π EXAMPLE 9: OUTLIER REMOVAL VIA IQR FILTERING")
print("=" * 65)
df = pd.DataFrame({
'salary': [50000, 55000, 60000, 62000, 58000, 1500000] # 1.5M is an outlier
})
Q1 = df['salary'].quantile(0.25)
Q3 = df['salary'].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
filtered_df = df.query("@lower_bound <= salary <= @upper_bound")
print(f"Original Count : {len(df)}")
print(f"Filtered Count : {len(filtered_df)} (Outlier removed)")
print("Cleaned Salaries:\n", filtered_df)
print("=" * 65)
if __name__ == "__main__":
run_outlier_removal()
Output:
=================================================================
π EXAMPLE 9: OUTLIER REMOVAL VIA IQR FILTERING
=================================================================
Original Count : 6
Filtered Count : 5 (Outlier removed)
Cleaned Salaries:
salary
0 50000
1 55000
2 60000
3 62000
4 58000
=================================================================
Real-Time Example 10: Pandas Data Wrangling & EDA Operations Reference Matrix
A comprehensive reference summary mapping Pandas data wrangling functions to their operational roles in exploratory data analysis and ML preprocessing pipelines.
Pandas Data Wrangling Reference Matrix
PANDAS DATA WRANGLING & EDA REFERENCE MATRIX:
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Operation / Method β Pandas Syntax β Primary Machine Learning Application β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Structural Profiling β df.info(), df.describe() β Inspecting data types, memory, and statistical ranges β
β Missing Value Count β df.isnull().sum() β Diagnosing columns requiring imputation β
β Missing Value Imputation β df['col'].fillna(val) β Filling null values with mean, median, or mode β
β Advanced Querying β df.query("condition") β Subsetting datasets based on multi-variable thresholds β
β GroupBy Aggregations β df.groupby().agg() β Multi-metric summary statistics by category β
β Relational Joins β pd.merge(df1, df2, on=...) β Combining transactional logs with demographic profiles β
β Reshaping β df.pivot_table() β Cross-tabulating metrics into wide-form feature matricesβ
β Time-Series Resampling β df.resample('D').mean() β Aggregating high-frequency logs to daily/monthly trends β
β String Accessor β df['str_col'].str.lower() β Cleaning and normalizing categorical text features β
β Outlier Filtering β df.query("Q1 - 1.5*IQR ...") β Removing extreme values to stabilize model training β
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β ENGINEERING BEST PRACTICES: β
β 1. Always execute EDA diagnostics before imputation to understand missingness mechanisms (MCAR vs MAR). β
β 2. Use vectorized string and arithmetic operations (.str, .dt) instead of iterating with `df.iterrows()`. β
β 3. Save memory on large CSV datasets by specifying explicit data types (`dtype=...`) during `pd.read_csv()`. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Engineering Best Practice: Master Pandas data wrangling to turn raw, imperfect datasets into clean, structured feature matrices ready for machine learning ingestion.