pythonintermediate
Pandas Custom Aggregation Functions
Pass custom lambda and named functions to .agg() for complex groupby aggregations.
pythonPress ⌘/Ctrl + Shift + C to copy
import pandas as pd
df = pd.DataFrame({'dept':['eng','eng','hr','hr','eng'],'salary':[90000,85000,60000,65000,95000],'yoe':[3,5,2,7,8]})
def iqr(s):
return s.quantile(0.75) - s.quantile(0.25)
result = df.groupby('dept').agg(
avg_salary=('salary','mean'),
max_salary=('salary','max'),
salary_iqr=('salary', iqr),
avg_yoe=('yoe','mean'),
headcount=('salary','count'),
)
print(result)Use Cases
- HR analytics
- financial reporting
- cohort analysis
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonintermediate
Pandas GroupBy Aggregation Examples
GroupBy operations with multiple aggregations, named aggregations, and transform for DataFrame analysis.
Best for: Sales reporting by region and time period
#pandas#groupby
pythonbeginner
Pandas Time-Series Resampling
Resample time-series data from daily to weekly/monthly frequencies with aggregation functions.
Best for: time-series analytics
#pandas#time-series
pythonintermediate
Grouped Time-Series with ffill
Forward-fill missing time-series values within groups to handle irregular measurement intervals.
Best for: IoT sensor data
#pandas#ffill
pythonbeginner
Pandas Pivot Table Summary
Create multi-level summary pivot tables from transactional data using pd.pivot_table.
Best for: sales reporting
#pandas#pivot-table