Signature
DataFrame.groupby(by, as_index=True)What it does
groupby separates rows that share a key, applies an aggregation or transformation, and combines the results. Selecting one column before aggregating keeps the output focused.
Parameters
bylabel, list, or array- The column or columns that define each group.
as_indexbool, optionaloptional- Whether grouping keys become the result index.
Returns
DataFrameGroupBy
Example
pythonDataFrame.groupby example
import pandas as pd
df = pd.DataFrame({
"team": ["red", "blue", "red"],
"score": [10, 12, 8],
})
print(df.groupby("team")["score"].mean())Output
team blue 12.0 red 9.0 Name: score, dtype: float64
Watch out for
- Selecting a column after grouping avoids aggregating unrelated numeric columns.
- Group keys with missing values are dropped by default; pass dropna=False to keep them.