How to Create Different Aggregations Using GroupBy, Agg & Dictionaries
Python
Here we want to create a new dataframe that sums the sales and counts the order numbers for each category in an existing dataframe.
We create a dictionary containing the columns we want to aggregate as keys and the aggregate we want to perform as the value. This can then be passed into the groupby agg function to create the new aggregated dataframe.
1| #Dictionary to declare aggregations to perform 2| aggregations = {'Sales':'sum', 'OrderNo':'count'} 3| 4| df_2 = df.groupby(['category'],as_index=False).agg(aggregations)
133
121
117
109