Data Aggregation
Python · GroupBy & SQL-Style Analytics
Theory
Aggregation collapses many values into one summary number. On a column (a Series) you call methods such as sum(), mean(), median(), min(), max(), std(), count() (non-missing values) and nunique() (distinct values). df['salary'].mean() returns the average salary; df['salary'].sum() the total. On a whole DataFrame, df.sum(numeric_only=True) gives one result per numeric column.
To compute several at once use agg(): df['salary'].agg(['sum', 'mean', 'min', 'max', 'count']) returns a small Series with one entry per function, and df.agg({'salary': ['sum', 'mean'], 'name': 'count'}) applies different functions per column. df.describe() gives count, mean, std, min, quartiles and max for every numeric column in one call. pandas skips NaN values by default, so mean() averages only the known values. When you need these summaries per category rather than for the whole column, use groupby().
Why we use it
Raw rows rarely answer business questions; summaries do - total revenue, average order value, number of customers. Aggregation methods compute them reliably in one line.
When to use it
Use them for whole-column summaries and quick sanity checks after loading data. For per-group summaries (per department, per month) combine them with groupby(); for a full statistical profile use describe().
How it works
- df['salary']
- Choose the summary: sum, mean, count ...
- Skip NaN values (default skipna=True)
- Several summaries needed? Yes: Use .agg(['sum', 'mean', ...]). No: Call one method like .mean().
- Summary value(s)
Syntax
df['col'].sum() / .mean() / .count() / .nunique()
df['col'].agg(['sum', 'mean', 'max'])
df.agg({'col1': 'sum', 'col2': ['min', 'max']})Example
print(df['salary'].mean())
print(df['salary'].agg(['min', 'max', 'mean']))Key points
- Works directly on a Series (a single column) or with agg() on a DataFrame
- describe() gives a full statistical summary in one call
- NaN values are skipped by default (skipna=True)
- count() counts non-missing values; len(df) counts all rows
- SQL equivalent: SELECT SUM(salary), AVG(salary), COUNT(salary), COUNT(DISTINCT dept) FROM t