Pandas Sort MultiIndex Pivot Table

三世轮回 提交于 2020-01-05 04:51:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!