Pandas Pro
Expert pandas developer specializing in efficient data manipulation, analysis, and transformation workflows with production-grade performance patterns.
Core Workflow
- Assess data structure — Examine dtypes, memory usage, missing values, data quality:
print(df.dtypes)
print(df.memory_usage(deep=True).sum() / 1e6, "MB")
print(df.isna().sum())
print(df.describe(include="all"))
- Design transformation — Plan vectorized operations, avoid loops, identify indexing strategy
- Implement efficiently — Use vectorized methods, method chaining, proper indexing
- Validate results — Check dtypes, shapes, null counts, and row counts:
assert result.shape[0] == expected_rows, f"Row count mismatch: {result.shape[0]}"
assert result.isna().sum().sum() == 0, "Unexpected nulls after transform"
assert set(result.columns) == expected_cols
- Optimize — Profile memory, apply categorical types, use chunking if needed
Reference Guide
Load detailed guidance based on context:
| Topic |
Reference |
Load When |
| DataFrame Operations |
references/dataframe-operations.md |
Indexing, selection, filtering, sorting |
| Data Cleaning |
references/data-cleaning.md |
Missing values, duplicates, type conversion |
| Aggregation & GroupBy |
references/aggregation-groupby.md |
GroupBy, pivot, crosstab, aggregation |
| Merging & Joining |
references/merging-joining.md |
Merge, join, concat, combine strategies |
| Performance Optimization |
references/performance-optimization.md |
Memory usage, vectorization, chunking |
Code Patterns
Vectorized Operations (before/after)
# ❌ AVOID: row-by-row iteration
for i, row in df.iterrows():
df.at[i, 'tax'] = row['price'] * 0.2
# ✅ USE: vectorized assignment
df['tax'] = df['price'] * 0.2
Safe Subsetting with .copy()
# ❌ AVOID: chained indexing triggers SettingWithCopyWarning
df['A']['B'] = 1
# ✅ USE: .loc[] with explicit copy when mutating a subset
subset = df.loc[df['status'] == 'active', :].copy()
subset['score'] = subset['score'].fillna(0)
GroupBy Aggregation
summary = (
df.groupby(['region', 'category'], observed=True)
.agg(
total_sales=('revenue', 'sum'),
avg_price=('price', 'mean'),
order_count=('order_id', 'nunique'),
)
.reset_index()
)
Merge with Validation
merged = pd.merge(
left_df, right_df,
on=['customer_id', 'date'],
how='left',
validate='m:1', # asserts right key is unique
indicator=True,
)
unmatched = merged[merged['_merge'] != 'both']
print(f"Unmatched rows: {len(unmatched)}")
merged.drop(columns=['_merge'], inplace=True)
Missing Value Handling
# Forward-fill then interpolate numeric gaps
df['price'] = df['price'].ffill().interpolate(method='linear')
# Fill categoricals with mode, numerics with median
for col in df.select_dtypes(include='object'):
df[col] = df[col].fillna(df[col].mode()[0])
for col in df.select_dtypes(include='number'):
df[col] = df[col].fillna(df[col].median())
Time Series Resampling
daily = (
df.set_index('timestamp')
.resample('D')
.agg({'revenue': 'sum', 'sessions': 'count'})
.fillna(0)
)
Pivot Table
pivot = df.pivot_table(
values='revenue',
index='region',
columns='product_line',
aggfunc='sum',
fill_value=0,
margins=True,
)
Memory Optimization
# Downcast numerics and convert low-cardinality strings to categorical
df['category'] = df['category'].astype('category')
df['count'] = pd.to_numeric(df['count'], downcast='integer')
df['score'] = pd.to_numeric(df['score'], downcast='float')
print(df.memory_usage(deep=True).sum() / 1e6, "MB after optimization")
Constraints
MUST DO
- Use vectorized operations instead of loops
- Set appropriate dtypes (categorical for low-cardinality strings)
- Check memory usage with
.memory_usage(deep=True)
- Handle missing values explicitly (don't silently drop)
- Use method chaining for readability
- Preserve index integrity through operations
- Validate data quality before and after transformations
- Use
.copy() when modifying subsets to avoid SettingWithCopyWarning
MUST NOT DO
- Iterate over DataFrame rows with
.iterrows() unless absolutely necessary
- Use chained indexing (
df['A']['B']) — use .loc[] or .iloc[]
- Ignore SettingWithCopyWarning messages
- Load entire large datasets without chunking
- Use deprecated methods (
.ix, .append() — use pd.concat())
- Convert to Python lists for operations possible in pandas
- Assume data is clean without validation
Output Templates
When implementing pandas solutions, provide:
- Code with vectorized operations and proper indexing
- Comments explaining complex transformations
- Memory/performance considerations if dataset is large
- Data validation checks (dtypes, nulls, shapes)
1---2name: pandas-pro3description: Performs pandas DataFrame operations for data analysis, manipulation, and transformation. Use when working with pandas DataFrames, data cleaning, aggregation, merging, or time series analysis. Invoke for data manipulation tasks such as joining DataFrames on multiple keys, pivoting tables, resampling time series, handling NaN values with interpolation or forward-fill, groupby aggregations, type conversion, or performance optimization of large datasets.4license: MIT5---67# Pandas Pro89Expert pandas developer specializing in efficient data manipulation, analysis, and transformation workflows with production-grade performance patterns.1011## Core Workflow12131. **Assess data structure** — Examine dtypes, memory usage, missing values, data quality:14 ```python15 print(df.dtypes)16 print(df.memory_usage(deep=True).sum() / 1e6, "MB")17 print(df.isna().sum())18 print(df.describe(include="all"))19 ```202. **Design transformation** — Plan vectorized operations, avoid loops, identify indexing strategy213. **Implement efficiently** — Use vectorized methods, method chaining, proper indexing224. **Validate results** — Check dtypes, shapes, null counts, and row counts:23 ```python24 assert result.shape[0] == expected_rows, f"Row count mismatch: {result.shape[0]}"25 assert result.isna().sum().sum() == 0, "Unexpected nulls after transform"26 assert set(result.columns) == expected_cols27 ```285. **Optimize** — Profile memory, apply categorical types, use chunking if needed2930## Reference Guide3132Load detailed guidance based on context:3334| Topic | Reference | Load When |35|-------|-----------|-----------|36| DataFrame Operations | `references/dataframe-operations.md` | Indexing, selection, filtering, sorting |37| Data Cleaning | `references/data-cleaning.md` | Missing values, duplicates, type conversion |38| Aggregation & GroupBy | `references/aggregation-groupby.md` | GroupBy, pivot, crosstab, aggregation |39| Merging & Joining | `references/merging-joining.md` | Merge, join, concat, combine strategies |40| Performance Optimization | `references/performance-optimization.md` | Memory usage, vectorization, chunking |4142## Code Patterns4344### Vectorized Operations (before/after)4546```python47# ❌ AVOID: row-by-row iteration48for i, row in df.iterrows():49 df.at[i, 'tax'] = row['price'] * 0.25051# ✅ USE: vectorized assignment52df['tax'] = df['price'] * 0.253```5455### Safe Subsetting with `.copy()`5657```python58# ❌ AVOID: chained indexing triggers SettingWithCopyWarning59df['A']['B'] = 16061# ✅ USE: .loc[] with explicit copy when mutating a subset62subset = df.loc[df['status'] == 'active', :].copy()63subset['score'] = subset['score'].fillna(0)64```6566### GroupBy Aggregation6768```python69summary = (70 df.groupby(['region', 'category'], observed=True)71 .agg(72 total_sales=('revenue', 'sum'),73 avg_price=('price', 'mean'),74 order_count=('order_id', 'nunique'),75 )76 .reset_index()77)78```7980### Merge with Validation8182```python83merged = pd.merge(84 left_df, right_df,85 on=['customer_id', 'date'],86 how='left',87 validate='m:1', # asserts right key is unique88 indicator=True,89)90unmatched = merged[merged['_merge'] != 'both']91print(f"Unmatched rows: {len(unmatched)}")92merged.drop(columns=['_merge'], inplace=True)93```9495### Missing Value Handling9697```python98# Forward-fill then interpolate numeric gaps99df['price'] = df['price'].ffill().interpolate(method='linear')100101# Fill categoricals with mode, numerics with median102for col in df.select_dtypes(include='object'):103 df[col] = df[col].fillna(df[col].mode()[0])104for col in df.select_dtypes(include='number'):105 df[col] = df[col].fillna(df[col].median())106```107108### Time Series Resampling109110```python111daily = (112 df.set_index('timestamp')113 .resample('D')114 .agg({'revenue': 'sum', 'sessions': 'count'})115 .fillna(0)116)117```118119### Pivot Table120121```python122pivot = df.pivot_table(123 values='revenue',124 index='region',125 columns='product_line',126 aggfunc='sum',127 fill_value=0,128 margins=True,129)130```131132### Memory Optimization133134```python135# Downcast numerics and convert low-cardinality strings to categorical136df['category'] = df['category'].astype('category')137df['count'] = pd.to_numeric(df['count'], downcast='integer')138df['score'] = pd.to_numeric(df['score'], downcast='float')139print(df.memory_usage(deep=True).sum() / 1e6, "MB after optimization")140```141142## Constraints143144### MUST DO145- Use vectorized operations instead of loops146- Set appropriate dtypes (categorical for low-cardinality strings)147- Check memory usage with `.memory_usage(deep=True)`148- Handle missing values explicitly (don't silently drop)149- Use method chaining for readability150- Preserve index integrity through operations151- Validate data quality before and after transformations152- Use `.copy()` when modifying subsets to avoid SettingWithCopyWarning153154### MUST NOT DO155- Iterate over DataFrame rows with `.iterrows()` unless absolutely necessary156- Use chained indexing (`df['A']['B']`) — use `.loc[]` or `.iloc[]`157- Ignore SettingWithCopyWarning messages158- Load entire large datasets without chunking159- Use deprecated methods (`.ix`, `.append()` — use `pd.concat()`)160- Convert to Python lists for operations possible in pandas161- Assume data is clean without validation162163## Output Templates164165When implementing pandas solutions, provide:1661. Code with vectorized operations and proper indexing1672. Comments explaining complex transformations1683. Memory/performance considerations if dataset is large1694. Data validation checks (dtypes, nulls, shapes)