pandas-pro
jeffallan/claude-skills
Expert pandas DataFrame operations for efficient data manipulation, cleaning, and analysis.
What is pandas-pro?
Pandas Pro is a specialized skill for performing vectorized DataFrame operations including data cleaning, aggregation, merging, pivoting, and time series analysis. Use it when working with pandas DataFrames to avoid common pitfalls like row iteration and chained indexing, and to optimize memory usage on large datasets.
- Perform vectorized DataFrame operations and transformations without row-by-row iteration
- Handle missing values with forward-fill, interpolation, and strategic imputation strategies
- Execute complex groupby aggregations, pivots, and crosstab operations with validation
- Merge and join DataFrames on multiple keys with cardinality validation and unmatched row detection
- Resample and analyze time series data with proper indexing and aggregation
- Optimize memory usage through dtype conversion, categorical encoding, and chunking strategies
How to install pandas-pro
npx skills add https://github.com/jeffallan/claude-skills --skill pandas-pro- pandas library installed
- Python 3.7 or later
- Basic familiarity with DataFrame concepts
How to use pandas-pro
- 1.Assess your DataFrame structure using dtypes, memory_usage(), isna().sum(), and describe()
- 2.Design your transformation plan identifying vectorized operations and indexing strategy
- 3.Implement using method chaining, .loc[]/.iloc[] for subsetting, and built-in aggregation methods
- 4.Validate results by checking shapes, null counts, dtypes, and row counts against expectations
- 5.Profile and optimize using categorical types, downcast numerics, and chunking for large datasets
Use cases
- Joining sales data from multiple sources on customer_id and date with validation of match rates
- Cleaning time series data by forward-filling missing prices then interpolating gaps
- Pivoting transaction records by region and product line to create summary revenue tables
- Aggregating user activity metrics grouped by region and category with multiple aggregation functions
- Converting large datasets to categorical types and downcasting numerics to reduce memory footprint
- Data analysts performing exploratory data analysis and cleaning
- Data engineers building production data pipelines
- Python developers working with tabular data in pandas
- Machine learning practitioners preparing datasets for model training
pandas-pro FAQ
Avoid iterrows() unless absolutely necessary. Vectorized operations are 10-100x faster. Use iterrows() only for complex logic that cannot be expressed with pandas methods, and consider apply() or numpy operations first.
Use .loc[] for explicit indexing and .copy() when modifying a subset: `subset = df.loc[df['status'] == 'active', :].copy()`. Avoid chained indexing like `df['A']['B'] = 1`.
Assess the pattern first with isna().sum(). For time series, use forward-fill then interpolate. For categoricals, fill with mode; for numerics, use median. Always validate the result.
Convert low-cardinality strings to categorical type, downcast numeric types with pd.to_numeric(..., downcast='integer'), and check memory_usage(deep=True) before and after. Consider chunking if the dataset exceeds available RAM.
Use the validate parameter to assert key cardinality (e.g., validate='m:1'), check the indicator column for unmatched rows, and compare row counts before and after the merge.
Full instructions (SKILL.md)
Source of truth, from jeffallan/claude-skills.
name: pandas-pro description: 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. license: MIT metadata: author: https://github.com/Jeffallan version: "1.1.0" domain: data-ml triggers: pandas, DataFrame, data manipulation, data cleaning, aggregation, groupby, merge, join, time series, data wrangling, pivot table, data transformation role: expert scope: implementation output-format: code related-skills: python-pro
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()— usepd.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)
Related skills
More from jeffallan/claude-skills and the wider catalog.
laravel-specialist
Build Laravel 10+ applications with Eloquent models, Sanctum auth, queues, APIs, and Livewire components.
golang-pro
Senior Go developer for concurrent systems, microservices, and production-grade performance optimization.
flutter-expert
Senior Flutter engineer for cross-platform apps with Riverpod, Bloc, GoRouter, and performance optimization.
php-pro
Senior PHP developer for modern PHP 8.3+, Laravel, Symfony with strict typing, PHPStan level 9, and enterprise patterns.
kubernetes-specialist
Deploy and manage Kubernetes workloads with secure manifests, RBAC, networking, and troubleshooting.
devops-engineer
Creates Dockerfiles, CI/CD pipelines, Kubernetes manifests, and infrastructure-as-code templates for deployment automation.