pbPassingBI
/

When would you use groupby().transform() instead of agg()?

intermediate
Answer

agg collapses each group to a single row. transform returns a result the same length as the input, aligned back onto every original row.

So transform is the pandas equivalent of a SQL window function. To add each row's share of its region's total:

df['pct'] = df['revenue'] / df.groupby('region')['revenue'].transform('sum')

With agg you would have to aggregate separately and merge the result back — more code, and another opportunity for a fan-out.

Related