jxn
jxn

Reputation: 8025

pandas groupby sort on summary statistics

    date    shown   clicked converted   avg_cost_per_click  total_revenue   ad
0   2015-10-01  65877   2339    43  0.90    641.62  ad_group_1
1   2015-10-02  65100   2498    38  0.94    756.37  ad_group_2
2   2015-10-03  70658   2313    49  0.86    970.90  ad_group_3
3   2015-10-04  69809   2833    51  1.01    907.39  ad_group_4
4   2015-10-05  68186   2696    41  1.00    879.45  ad_group_5

This is my dataframe df

i group by 'ad' and then i want to sort the output when i get the mean, max ect..

df_ad = df.groupby('ad')

How do i sort the below?

df_ad['shown'].mean().sort(ascending=True)

Upvotes: 1

Views: 1101

Answers (1)

Nickil Maveli
Nickil Maveli

Reputation: 29711

You need to aggregate the mean on every grouped key and use sort_values to sort those output values.

df_grouped = df.groupby(['ad'])['shown'].agg({'mean': np.mean, 'max': np.max})
df_grouped.sort_values(['mean', 'max'], ascending=[True, False], inplace=True)

Upvotes: 2

Related Questions