Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Data cleaning, transformation, and exploratory analysis with pandas
.claude/skills/brycewang-stanford-pandas-data-wrangling/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-03 | ✗→✓ | ▲ Improved | 136% | 0% |
| case-11 | ✗→✓ | ▲ Improved | 153% | 0% |
| case-12 | ✗→✓ | ▲ Improved | 62% | 0% |
| case-13 | ✗→✓ | ▲ Improved | 131% | 0% |
| case-14 | ✓→✓ | = Same ✓ | 56% | 0% |
Data wrangling -- the process of cleaning, transforming, and preparing raw data for analysis -- typically consumes 60-80% of a data scientist's time. Pandas is the de facto standard library for tabular data manipulation in Python, and mastering its idioms directly translates to faster, more reliable research workflows.
This guide covers the essential pandas operations that researchers encounter daily: loading heterogeneous data sources, diagnosing data quality issues, handling missing values, reshaping data for analysis, and performing exploratory data analysis (EDA). Each section includes copy-paste code examples designed for real-world research datasets.
Whether you are cleaning survey responses, preprocessing experimental logs, merging datasets from multiple sources, or preparing features for machine learning, the patterns here will save hours of trial and error.
pythonimport pandas as pd import numpy as np # CSV with encoding and date parsing df = pd.read_csv('data.csv', encoding='utf-8', parse_dates=['timestamp'], dtype={'participant_id': str}) # Excel with specific sheet df = pd.read_excel('data.xlsx', sheet_name='Experiment1', header=1) # Skip first row # JSON (nested) df = pd.json_normalize(json_data, record_path='results', meta=['experiment_id', 'date']) # Parquet (fast, columnar) df = pd.read_parquet('data.parquet')
python# Shape and types print(f"Shape: {df.shape}") print(df.dtypes) print(df.info(memory_usage='deep')) # Statistical summary print(df.describe(include='all')) # Missing value report missing = df.isnull().sum() missing_pct = (missing / len(df) * 100).round(1) missing_report = pd.DataFrame({ 'count': missing, 'percent': missing_pct }).query('count > 0').sort_values('percent', ascending=False) print(missing_report) # Duplicate check n_dupes = df.duplicated().sum() print(f"Duplicate rows: {n_dupes}")
| Situation | Strategy | pandas Method | |-----------|----------|---------------| | < 5% missing, random | Drop rows | df.dropna() | | Numeric, moderate missing | Mean/median imputation | df.fillna(df.median()) | | Categorical missing | Mode or "Unknown" | df.fillna('Unknown') | | Time series gaps | Forward/backward fill | df.ffill() / df.bfill() | | Systematic missing | Multiple imputation | sklearn.impute.IterativeImputer | | Feature > 50% missing | Drop column | df.drop(columns=[...]) |
python# Conditional imputation df['age'] = df['age'].fillna(df.groupby('group')['age'].transform('median')) # Interpolation for time series df['temperature'] = df['temperature'].interpolate(method='time') # Flag missing values before imputing (preserve information) df['salary_missing'] = df['salary'].isnull().astype(int) df['salary'] = df['salary'].fillna(df['salary'].median())
python# String cleaning df['name'] = df['name'].str.strip().str.lower() df['email'] = df['email'].str.replace(r'\s+', '', regex=True) # Categorical conversion (saves memory, enables ordering) df['education'] = pd.Categorical( df['education'], categories=['high_school', 'bachelors', 'masters', 'phd'], ordered=True ) # Numeric extraction from text df['value'] = df['text_field'].str.extract(r'(\d+\.?\d*)').astype(float)
python# Wide to long (unpivot) df_long = pd.melt(df, id_vars=['subject_id', 'condition'], value_vars=['score_t1', 'score_t2', 'score_t3'], var_name='timepoint', value_name='score' ) # Long to wide (pivot) df_wide = df_long.pivot_table( index='subject_id', columns='condition', values='score', aggfunc='mean' ).reset_index() # Cross-tabulation ct = pd.crosstab(df['group'], df['outcome'], margins=True, normalize='index')
python# Left join with validation merged = pd.merge( experiments, participants, on='participant_id', how='left', validate='many_to_one', # Catch unexpected duplicates indicator=True # Shows _merge column ) # Check merge quality print(merged['_merge'].value_counts())
pythondef quick_eda(df, target_col=None): """Run a quick EDA pipeline on a DataFrame.""" print(f"=== Shape: {df.shape} ===\n") # Numeric columns numeric_cols = df.select_dtypes(include=np.number).columns print(f"Numeric columns ({len(numeric_cols)}):") print(df[numeric_cols].describe().round(2)) # Categorical columns cat_cols = df.select_dtypes(include=['object', 'category']).columns print(f"\nCategorical columns ({len(cat_cols)}):") for col in cat_cols: n_unique = df[col].nunique() print(f" {col}: {n_unique} unique values") if n_unique <= 10: print(f" {df[col].value_counts().to_dict()}") # Correlations with target if target_col and target_col in numeric_cols: corr = df[numeric_cols].corr()[target_col].drop(target_col) print(f"\nCorrelations with '{target_col}':") print(corr.sort_values(ascending=False).round(3)) quick_eda(df, target_col='accuracy')
python# Multi-metric summary by group summary = df.groupby('method').agg( mean_acc=('accuracy', 'mean'), std_acc=('accuracy', 'std'), median_time=('runtime_sec', 'median'), n_runs=('run_id', 'count') ).round(3).sort_values('mean_acc', ascending=False) print(summary.to_markdown())
| Technique | When to Use | Speedup | |-----------|-------------|---------| | pd.Categorical for strings | Repeated string values | 2-10x memory | | .query() instead of boolean indexing | Complex filters | 1.5-3x | | pd.eval() for arithmetic | Column arithmetic | 2-5x | | Parquet instead of CSV | Large datasets | 5-20x I/O | | df.pipe() for chaining | Readable pipelines | Clarity |
python# Method chaining with pipe result = ( df .query('score > 0') .assign(log_score=lambda x: np.log1p(x['score'])) .groupby('group') .agg(mean_log=('log_score', 'mean')) .sort_values('mean_log', ascending=False) )
.copy() when creating derived datasets._merge indicator column.df.memory_usage(deep=True) to identify memory bottlenecks.| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-14 | pass→pass | 10,941 | 6,243 | -43% | 1 | 1 | 0% | 2,119 | 3,296 | +56% | 0 | 0 | — |
case-15 | pass→pass | 12,422 | 6,908 | -44% | 1 | 1 | 0% | 1,881 | 3,272 | +74% | 0 | 0 | — |
case-16 | fail→fail | 8,611 | 9,674 | +12% | 1 | 1 | 0% | 1,513 | 3,919 | +159% | 0 | 0 | — |
case-17 | fail→fail | 7,632 | 6,401 | -16% | 1 | 1 | 0% | 1,426 | 3,134 | +120% | 0 | 0 | — |
case-01 | fail→fail | 10,170 | 14,028 | +38% | 1 | 1 | 0% | 2,072 | 3,705 | +79% | 0 | 0 | — |
case-02 | fail→fail | 23,040 | 26,873 | +17% | 1 | 1 | 0% | 4,885 | 7,892 | +62% | 0 | 0 | — |
case-03 | fail→pass | 8,351 | 9,910 | +19% | 1 | 1 | 0% | 1,553 | 3,671 | +136% | 0 | 0 | — |
case-04 | fail→fail | 7,403 | 7,335 | -1% | 1 | 1 | 0% | 1,317 | 3,387 | +157% | 0 | 0 | — |
case-18 | pass→pass | 14,135 | 8,964 | -37% | 1 | 1 | 0% | 2,003 | 3,592 | +79% | 0 | 0 | — |
case-05 | pass→pass | 5,594 | 4,418 | -21% | 1 | 1 | 0% | 920 | 2,828 | +207% | 0 | 0 | — |
case-06 | pass→pass | 7,905 | 6,360 | -20% | 1 | 1 | 0% | 1,422 | 3,265 | +130% | 0 | 0 | — |
case-07 | pass→pass | 11,228 | 11,424 | +2% | 1 | 1 | 0% | 2,084 | 4,257 | +104% | 0 | 0 | — |
case-08 | pass→pass | 12,593 | 13,353 | +6% | 1 | 1 | 0% | 2,194 | 4,388 | +100% | 0 | 0 | — |
case-09 | pass→pass | 9,495 | 8,851 | -7% | 1 | 1 | 0% | 1,713 | 3,720 | +117% | 0 | 0 | — |
case-10 | pass→pass | 8,617 | 8,478 | -2% | 1 | 1 | 0% | 1,776 | 3,414 | +92% | 0 | 0 | — |
case-11 | fail→pass | 7,685 | 9,371 | +22% | 1 | 1 | 0% | 1,529 | 3,864 | +153% | 0 | 0 | — |
case-12 | fail→pass | 9,990 | 6,493 | -35% | 1 | 1 | 0% | 1,993 | 3,223 | +62% | 0 | 0 | — |
case-13 | fail→pass | 11,060 | 9,165 | -17% | 1 | 1 | 0% | 1,698 | 3,922 | +131% | 0 | 0 | — |
case-19 | pass→pass | 9,434 | 7,632 | -19% | 1 | 1 | 0% | 1,798 | 3,513 | +95% | 0 | 0 | — |
case-20 | pass→pass | 12,780 | 15,177 | +19% | 1 | 1 | 0% | 2,618 | 4,999 | +91% | 0 | 0 | — |
case-21 | fail→fail | 16,279 | 13,674 | -16% | 1 | 1 | 0% | 2,046 | 4,685 | +129% | 0 | 0 | — |
case-22 | pass→pass | 9,715 | 8,694 | -11% | 1 | 1 | 0% | 1,811 | 3,744 | +107% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 22 cases were attempted. The headline lift of +18 percentage points is the difference between those two pass rates over the 22 comparable cases.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.