简体   繁体   English

按边距('All')值列对Pandas Pivot Table进行排序

[英]Sort Pandas Pivot Table by the margin ('All') values column

I'm trying to do a descending sort on the last column/margins/aggrfunc by the sum of the rows in a pandas pivot table. 我试图通过pandas数据透视表中的行总和对最后一列/ margin / aggrfunc进行降序排序。 I know I'm missing something simple here, but I can't figure it out. 我知道我在这里缺少一些简单的东西,但我无法弄明白。

dataframe/pivot table: dataframe / pivot表:

WIDGETS         
DATE    2/1/16  2/2/16  2/3/16  All
NAME                
PERSON1 43      5               48
PERSON2         4       7       11
PERSON3         56      143     199

What I need it to do is also sort by aggfunc/margins: 我需要做的还是通过aggfunc / margin来排序:

WIDGETS         
DATE    2/1/16  2/2/16  2/3/16  All
NAME                
PERSON3         56      143     199
PERSON1 43      5               48
PERSON2         4       7       11

pt = pd.pivot_table(df,values=['WIDGETS'],index=['NAME'],columns=['DATE'],aggfunc=len,fill_value='',margins=True,margins_name='WIDGETS')
pt.sort_values(by='WIDGETS',ascending=False,inplace=True)

Error: ValueError: Cannot sort by column WIDGETS in a multi-index you need to explicity provide all the levels 错误: ValueError:无法按多列索引中的列WIDGETS排序,您需要明确提供所有级别

Suggestions? 建议?

You can use tuple in function sort_values and parameter ascending : 您可以在函数sort_values和参数ascending使用元组:

print pt
        WIDGETS                  
DATE     2/1/16 2/2/16 2/3/16 All
NAME                             
PERSON1       1      2          3
PERSON2       2      4      3   9
PERSON3       1             1   2
All           4      6      4  14

pt.sort_values(by=('WIDGETS', 'All'), ascending=False,inplace=True)
print pt
        WIDGETS                  
DATE     2/1/16 2/2/16 2/3/16 All
NAME                             
All           4      6      4  14
PERSON2       2      4      3   9
PERSON1       1      2          3
PERSON3       1             1   2

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

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