简体   繁体   English

Pandas 数据透视表嵌套排序第 2 部分

[英]Pandas pivot table Nested Sorting Part 2

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

I want to sort the pivot table such that the values are sorted descendingly within 'C'.我想对数据透视表进行排序,以便在“C”中对值进行降序排序。

Like this:像这样:

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

Thanks in advance!提前致谢!

try this:尝试这个:

In [12]: pd.pivot_table(df, index=['A', 'B'],aggfunc='sum').reset_index().sort_values(by=['A','C'], ascending=[1,0])
Out[12]:
   A    B  C
0  x  one  7
1  x  two  4
2  y  one  5
3  y  two  1
5  z  two  6
4  z  one  3

这应该工作

df.groupby(['A'])['B', 'C'].apply(lambda x: x.set_index('B').sort_values('C', ascending=0))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM