问题
Given the following pivot table:
import pandas as pd
import numpy as np
df = pd.DataFrame(
{'YYYYMM':[201603,201503,201403,201303,201603,201503,201403,201303],
'Count':[5,6,2,7,4,7,8,9],
'Group':['A','A','A','A','B','B','B','B']})
df['YYYYMM']=df['YYYYMM'].astype(str).str[:-2].astype(np.int64)
t=df.pivot_table(df,index=['Group'],columns=['YYYYMM'],aggfunc=np.sum)
t
Count
YYYYMM 2013 2014 2015 2016
Group
A 7 2 6 5
B 9 8 7 4
I'd like to sort the rows (groups A and B) ascendingly by 2016 such that group B is above group A, while retaining the overall layout of the pivot table.
Thanks in advance!
回答1:
Use sort_values
t.sort_values(('Count', 2016))
the tuple ('Count', 2016)
is the name of the column you want to sort by.
looks like:
Count
YYYYMM 2013 2014 2015 2016
Group
B 9 8 7 4
A 7 2 6 5
来源:https://stackoverflow.com/questions/37309652/pandas-sort-multiindex-pivot-table