It's easy to produces multi-level groupby result like this
Max Speed
Animal Type
Falcon Captive 390.0
Wild 350.0
Parrot Captive 30.0
Wild 20.0
The code would look like df.groupby(['animal', 'type'])['speed'].max()
However, if I want to add a total row to each subgroup, to produce something like this
Max Speed
Animal Type
Falcon Captive 390.0
Wild 350.0
overall 390.0
Parrot Captive 30.0
Wild 20.0
overall 30.0
How can I do it?
The reason for adding the sub-level-row, is that it enables choosing category when I put it into BI tools for other colleagues.
UPDATE: in the example above I show using max()
, I also want to know how to do it with user_id.nunique()
.
Right now I produce the result by 2 groupby and then concat them. something like
df1 = df.groupby(['animal', 'type'])['speed'].max()
df2 = df.groupby(['animal'])['speed'].max()
##### ... manually add `overall` index to df_2
df_total = pd.concat([df1, df2]).sort_index()
but it seems bit too manual, is there better approach?