Groupby and aggregation
Quick answer
Grouping partitions rows by a key and aggregation reduces each group to a summary. A groupby result has a different grain from the source. size counts all rows; count counts nonmissing values in a selected column. Use an explicit missing-key policy and denominator for every feature or metric. Examples run locally on Python 3.13.5 and pandas 2.2.3; ByteMind package support is not verified. All data are synthetic.
Profile groups with different missingness
Keep missing group keys with dropna=False. Named aggregation specifies the input column and summary operation for each output field.
import pandas as pdx = pd.DataFrame({'site': ['a', 'a', 'b', None], 'temp': [20, None, 30, 40]})g = x.groupby('site', dropna=False, sort=False).agg(rows=('temp', 'size'), observed=('temp', 'count'), mean=('temp', 'mean'))print(g['rows'].tolist())print(g['observed'].tolist())print(g['mean'].tolist())Expected output (pandas 2.2.3):
[2, 1, 1][1, 1, 1][20.0, 30.0, 40.0]Site a has two rows but one observed reading. Its mean uses one value, so it should not be interpreted as equally reliable as a mean from many observations.
Reshape summaries with pivot_table
Pivoting moves categories into columns. pivot_table aggregates repeated combinations; plain pivot requires unique index-column combinations.
import pandas as pdx = pd.DataFrame({'site': ['a', 'a', 'a', 'b'], 'shift': ['day', 'day', 'night', 'day'], 'count': [2, 4, 1, 5]})p = x.pivot_table(index='site', columns='shift', values='count', aggfunc='sum', observed=True)print(p.loc['a'].tolist())print(pd.isna(p.loc['b', 'night']))print(p.reset_index().columns.tolist())Expected output (pandas 2.2.3):
[6.0, 1.0]True['site', 'day', 'night']The absent b-night combination is missing, not automatically zero. Fill only when absence really means zero. melt can convert wide columns back into named variable/value rows, but aggregation may have lost original detail.
Common mistakes
For categorical groupers, observed=True limits grouping to observed categories; set it explicitly rather than relying on version-dependent defaults. dropna and observed solve different problems. When creating group-level target features, never aggregate across holdout rows or future outcomes. All-missing sums may be zero by default; use sum(min_count=1) when absence should remain missing.
Practice and next steps
Create a profile that reports rows and observed values per shift. Explain why a mean alone hides missingness. Try the pure-Python reasoning challenge and knowledge check separately; these do not assess pandas API execution.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Groupby and aggregation — knowledge check
Apply tabular data reasoning to new synthetic fixtures.
A group has [3,None,0]. What are size and count?
What is the observed mean for [4,None,8]?
How can groupby retain missing group keys?
Which method can aggregate repeated pivot coordinates?
What does a missing site-shift combination imply?