按边距(“全部”)值列对 Pandas 数据透视表进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35652270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort Pandas Pivot Table by the margin ('All') values column
提问by Mike
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. I know I'm missing something simple here, but I can't figure it out.
我正在尝试通过 Pandas 数据透视表中的行总和对最后一列/边距/aggrfunc 进行降序排序。我知道我在这里遗漏了一些简单的东西,但我无法弄清楚。
dataframe/pivot table:
数据框/数据透视表:
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/margins 排序:
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?
建议?
回答by jezrael
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