| name | pandas-coder |
| description | DataFrame manipulation with chunked processing, memory optimization, and vectorized operations. |
| allowed-tools | Read Write Edit Grep Glob Bash |
Pandas-Coder
Expert in pandas DataFrame manipulation with focus on production-ready patterns for large datasets.
Memory-Efficient Reading
chunks = pd.read_csv('large.csv', chunksize=50_000)
for chunk in chunks:
process(chunk)
df = pd.read_csv('data.csv', usecols=['id', 'name', 'value'])
df = pd.read_csv('data.csv', dtype={
'id': 'int32',
'category': 'category',
'flag': 'bool'
})
Category Type for Repeated Strings
df['status'] = df['status'].astype('category')
df['status'] = pd.Categorical(
df['status'],
categories=['pending', 'active', 'completed', 'cancelled']
)
Vectorized Operations Over Loops
for idx, row in df.iterrows():
df.loc[idx, 'total'] = row['price'] * row['qty']
df['total'] = df['price'] * df['qty']
df['clean'] = df['name'].apply(lambda x: x.strip().lower())
df['clean'] = df['name'].str.strip().str.lower()
Conditional Assignment
df['tier'] = np.where(df['revenue'] > 1000, 'premium', 'standard')
conditions = [
df['score'] >= 90,
df['score'] >= 70,
df['score'] >= 50
]
choices = ['A', 'B', 'C']
df['grade'] = np.select(conditions, choices, default='F')
GroupBy Optimizations
result = df.groupby('category').agg(
total_sales=('sales', 'sum'),
avg_price=('price', 'mean'),
count=('id', 'count')
)
df['pct_of_group'] = df.groupby('category')['value'].transform(
lambda x: x / x.sum()
)
Index Operations
df = df.set_index('user_id')
user_data = df.loc[12345]
df.reset_index(drop=True, inplace=True)
df = df.set_index(['region', 'date'])
df.loc[('US', '2024-01')]
Memory Reduction Recipe
def reduce_memory(df: pd.DataFrame) -> pd.DataFrame:
"""Reduce DataFrame memory by 50-90%."""
for col in df.columns:
col_type = df[col].dtype
if col_type == 'object':
if df[col].nunique() / len(df) < 0.5:
df[col] = df[col].astype('category')
elif col_type == 'int64':
if df[col].min() >= 0:
if df[col].max() < 255:
df[col] = df[col].astype('uint8')
elif df[col].max() < 65535:
df[col] = df[col].astype('uint16')
else:
if df[col].min() > -128 and df[col].max() < 127:
df[col] = df[col].astype('int8')
elif df[col].min() > -32768 and df[col].max() < 32767:
df[col] = df[col].astype('int16')
elif col_type == 'float64':
df[col] = df[col].astype('float32')
return df
Parquet Over CSV
df.to_parquet('data.parquet', compression='snappy', index=False)
df = pd.read_parquet('data.parquet', columns=['id', 'value'])
df.to_parquet(
'data/',
partition_cols=['year', 'month'],
compression='snappy'
)
DateTime Handling
df['date'] = pd.to_datetime(df['date_str'], format='%Y-%m-%d')
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['weekday'] = df['date'].dt.day_name()
df['days_ago'] = (pd.Timestamp.now() - df['date']).dt.days
Merge Optimization
left = left.sort_values('key')
right = right.sort_values('key')
result = pd.merge(left, right, on='key')
for df in [left, right]:
df['key'] = df['key'].astype('category')
Query vs Boolean Indexing
filtered = df[(df['status'] == 'active') & (df['value'] > 100)]
filtered = df.query('status == "active" and value > 100')
min_val = 100
filtered = df.query('value > @min_val')
JSON Flattening
Normalize nested JSON structures into tabular format.
Flattening Strategies
- Dot Notation (Full Flatten) -
user.address.city column naming
- Array Explosion - One row per array element, parent fields duplicated
- Selective Flatten - Keep complex nested paths as JSON columns
Core Implementation
def flatten_json(
data: dict,
parent_key: str = '',
sep: str = '.',
max_depth: int = None,
current_depth: int = 0
) -> dict:
"""Recursively flatten nested JSON."""
items = {}
for key, value in data.items():
new_key = f"{parent_key}{sep}{key}" if parent_key else key
if isinstance(value, dict):
if max_depth is None or current_depth < max_depth:
items.update(flatten_json(value, new_key, sep, max_depth, current_depth + 1))
else:
items[new_key] = value
elif isinstance(value, list):
items[new_key] = value
else:
items[new_key] = value
return items
def explode_arrays(df: pd.DataFrame, array_columns: list[str]) -> pd.DataFrame:
"""Explode array columns into separate rows."""
for col in array_columns:
df = df.explode(col).reset_index(drop=True)
if df[col].apply(lambda x: (x, )).():
expanded = pd.json_normalize(df[col])
expanded.columns = [ c expanded.columns]
df = pd.concat([df.drop(col, axis=), expanded], axis=)
df
() -> pd.DataFrame:
flattened = [flatten_json(record, max_depth=max_depth) record json_data]
df = pd.DataFrame(flattened)
array_columns:
df = explode_arrays(df, array_columns)
df
SQL JSON Flattening (PostgreSQL)
SELECT
id,
json_data->>'name' as name,
json_data->'address'->>'city' as city,
(json_data->>'created_at')::timestamp as created_at
FROM source_table;
SELECT
id,
item->>'sku' as sku,
(item->>'quantity')::int as quantity
FROM source_table,
LATERAL jsonb_array_elements(data->'items') as item;
dbt JSON Flattening
{{ config(materialized='view') }}
with source as (
select * from {{ source('raw', 'api_events') }}
),
flattened as (
select
id,
json_data->>'event_type' as event_type,
json_data->'user'->>'id' as user_id,
json_data->'user'->>'email' as user_email,
json_data->'properties' as properties_json
from source
)
select * from flattened
Output Schema Generation
flattened_schema:
source: events.json
original_depth: 4
flattening_strategy: dot_notation
array_handling: explode
columns:
- path: user.name
original_path: ["user", "name"]
type: string
nullable: false
- path: items.sku
original_path: ["items", "[*]", "sku"]
type: string
note: "Exploded from array"
row_multiplication:
source_rows: 1000
output_rows: 3500
reason: "items array avg 3.5 elements"