Pandas Sort MultiIndex Pivot Table

2019-07-25 01:52发布

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条回答
你好瞎i
2楼-- · 2019-07-25 02:06

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
查看更多
登录 后发表回答