pandas 排序MultiIndex数据透视表 [英] Pandas Sort MultiIndex Pivot Table

查看:62
本文介绍了 pandas 排序MultiIndex数据透视表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下数据透视表:

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

我想在2016年之前对行(A和B组)进行升序排序,以使B组高于A组,同时保留数据透视表的总体布局.

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.

提前谢谢!

推荐答案

使用sort_values

t.sort_values(('Count', 2016))

元组('Count', 2016)是您要作为排序依据的列的名称.

the tuple ('Count', 2016) is the name of the column you want to sort by.

看起来像:

       Count               
YYYYMM  2013 2014 2015 2016
Group                      
B          9    8    7    4
A          7    2    6    5

这篇关于 pandas 排序MultiIndex数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆