How to Create Different Aggregations Using GroupBy, Agg & Dictionaries


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'}
 4|  df_2 = df.groupby(['category'],as_index=False).agg(aggregations)
Did you find this snippet useful?

Sign up for free to to add this to your code library