I am trying to do a groupby using Pandas and apply a sort. Something like below:
I have so far created the individual frames to get the subtotals. Not sure how to proceed after that to get the sorting done properly without resorting to hacks.
Sample dataframe is from this previous question.
df = pd.DataFrame({
'admin0': ['cntry1', 'cntry1', 'cntry1', 'cntry1', 'cntry1', 'cntry1', 'cntry2', 'cntry2', 'cntry2', 'cntry2', 'cntry2'],
'admin1': ['state1', 'state1', 'state1', 'state2', 'state2', 'state2', 'state3', 'state3', 'state3', 'state3', 'state4'],
'admin2': ['city1', 'city1', 'city2', 'city3', 'city4', 'city4', 'city5', 'city6', 'city6', 'city6', 'city7'],
'windspeed': [60, 90, 60, 60, 60, 90, 60, 60, 90, 120, 60],
'population': [700, 210, 100, 70, 180, 370, 890, 120, 420, 360, 740]
})
g1 = df.groupby(['admin0', 'admin1', 'admin2']).sum()
g2 = g1.groupby(level=[0, 1]).sum()
g2.index = pd.MultiIndex.from_arrays([g2.index.get_level_values(0), g2.index.get_level_values(1), len(g2.index)*['']])
g3 = g1.groupby(level=0).sum()
g3.index = pd.MultiIndex.from_arrays([g3.index.get_level_values(0), len(g3.index)*[''], len(g3.index)*['']])
g = pd.concat([g1, g2, g3])
State of g now:
windspeed population
admin0 admin1 admin2
cntry1 state1 city1 150 910
city2 60 100
state2 city3 60 70
city4 150 550
cntry2 state3 city5 60 890
city6 270 900
state4 city7 60 740
cntry1 state1 210 1010
state2 210 620
cntry2 state3 330 1790
state4 60 740
cntry1 420 1630
cntry2 390 2530
I now want to be able to sort without changing the grouping as shown in the gif.
Expected response when grouping by windspeed ascending:
windspeed population
admin0 admin1 admin2
cntry2 390 2530
state4 60 740
city7 60 740
state3 330 1790
city5 60 890
city6 270 900
cntry1 420 1630
state1 210 1010
city2 60 100
city1 150 910
state2 210 620
city3 60 70
city4 150 550