Sub topic 3
Naming Aggregated Columns
This chapter assumes you can create a pandas DataFrame, select columns, and distinguish a Series from a DataFrame. The examples use the sales DataFrame df from earlier chapters.
Naming aggregated columns
groupby creates groups, and agg calculates summaries for each group. Named aggregation assigns clear names to the output columns:
summary = df.groupby("region").agg(
total_units=("units", "sum"),
average_price=("price", "mean"),
order_count=("product", "size"),
)
print(summary)Each output name is followed by the source column and the aggregation function. This is easier to read than default names such as units_sum.
Sorting a grouped summary
A grouped result is still a DataFrame, so sort it with sort_values:
summary = summary.sort_values("total_units", ascending=False)
print(summary)The region remains the index. Use sort_index() when you want alphabetical order by region instead:
print(summary.sort_index())Missing values in summaries and groups
Most numeric aggregations skip missing values. For example, sum adds the available units values. size counts rows, including rows whose selected values are missing. count counts only non-missing values.
By default, groupby excludes rows whose grouping key is missing. Use dropna=False to keep a missing-key group:
summary = df.groupby("region", dropna=False).agg(
total_units=("units", "sum"),
nonmissing_units=("units", "count"),
order_count=("product", "size"),
)Adding group statistics with `transform`
agg produces one row per group. transform produces a value for every original row, aligned with df:
df["region_total"] = df["units"].groupby(df["region"]).transform("sum")
df["region_share"] = df["units"] / df["region_total"]
print(df[["region", "units", "region_total", "region_share"]])This makes group comparisons possible without losing the original rows.
Reshaping summaries with `pivot_table`
pivot_table creates a cross-tabulated summary. This example shows total units for each product within each region:
table = df.pivot_table(
index="region",
columns="product",
values="units",
aggfunc="sum",
fill_value=0,
)
print(table)fill_value=0 replaces empty region-product combinations with zero. Without it, those combinations usually appear as missing values.
Exercise
Which method should you use when you need one group total repeated on every original row?
Show answer
Use transform, because it returns values aligned with the original DataFrame.