pandas 数据透视表嵌套排序 [英] Pandas pivot table Nested Sorting

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

问题描述

给出此数据框和数据透视表:

Given this data frame and pivot table:

import pandas as pd
df=pd.DataFrame({'A':['x','y','z','x','y','z'],
                 'B':['one','one','one','two','two','two'],
                 'C':[7,5,3,4,1,6]})
df


    A   B       C
0   x   one     7
1   y   one     5
2   z   one     3
3   x   two     4
4   y   two     1
5   z   two     6

table = pd.pivot_table(df, index=['A', 'B'],aggfunc=np.sum)

table
A  B  
x  one    7
   two    4
y  one    5
   two    1
z  one    3
   two    6
Name: C, dtype: int64

我想对数据透视表进行排序,以使"A"的顺序为z,x,y,而"B"的顺序基于数据帧列"C"中的降序排序值.

I want to sort the pivot table such that the order of 'A' is z, x, y and the order of 'B' is based on the descendingly-sorted values from data frame column 'C'.

喜欢这个:

A  B  
z  two    6
   one    3
x  one    7
   two    4
y  one    5
   two    1

    Name: C, dtype: int64

提前谢谢!

推荐答案

我不认为有一种简单的方法可以实现您的目标.以下解决方案首先根据列C的值对表以降序排序.然后,它会根据您想要的顺序将每个切片连接起来.

I don't believe there is an easy way to accomplish your objective. The following solution first sorts your table is descending order based on the values of column C. It then concatenates each slice based on your desired order.

order = ['z', 'x', 'y']
table = table.reset_index().sort_values('C', ascending=False)
>>> pd.concat([table.loc[table.A == val, :].set_index(['A', 'B']) for val in order])
       C
A B     
z two  6
  one  3
x one  7
  two  4
y one  5
  two  1

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

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