How to Create Different Aggregations Using GroupBy, Agg & Dictionaries

Python
Data Preprocessing

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)
2 Upvotes
Tags: Groupby | Agg
Did you find this snippet useful?

Sign up to bookmark this in your snippet library

Normalize Windowed Time Series
Python
Data Preprocessing

Scaler | Normalize | Scale | Min-max

4
Pivoting Pandas Dataframes
Python
Data Preprocessing

Pandas

3
2