Python Pandas pivot_table,按列对值进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41119623/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:28:01  来源:igfitidea点击:

Pandas pivot_table, sort values by columns

pythonpandasindexingpivot-table

提问by Kah

I am a new user to Pandas and I love it!

我是 Pandas 的新用户,我喜欢它!

I am trying to create a pivot table in Pandas. Once I have pivot table the way I want, I would like to rank the values by the columns.

我正在尝试在 Pandas 中创建一个数据透视表。按照我想要的方式创建数据透视表后,我想按列对值进行排名。

I've attached an image from Excel as it is easier to see in tabular format what I am trying to achieve. Link to image

我附上了一张来自 Excel 的图片,因为它更容易以表格格式查看我想要实现的目标。图片链接

I've searched through stackoverflow but am having trouble finding an answer. I tried using .sort() but this doesn't work. Any help will be appreciated.

我已经通过 stackoverflow 进行了搜索,但找不到答案。我尝试使用 .sort() 但这不起作用。任何帮助将不胜感激。

Thanks in advance

提前致谢

回答by Algold

This should do what you are looking for:

这应该做你正在寻找的:

In [1]: df = pd.DataFrame.from_dict([{'Country': 'A', 'Year':2012, 'Value': 20, 'Volume': 1}, {'Country': 'B', 'Year':2012, 'Value': 100, 'Volume': 2}, {'Country': 'C', 'Year':2013, 'Value': 40, 'Volume': 4}])

In [2]: df_pivot = pd.pivot_table(df, index=['Country'], columns = ['Year'],values=['Value'], fill_value=0)

In [3]: df_pivot
Out [4]:
    Value     
Year     2012 2013
Country           
A          20    0
B         100    0
C           0   40

In [5]: df = df_pivot.reindex(df_pivot['Value'].sort_values(by=2012, ascending=False).index)

Out [6]: 
    Value     
Year     2012 2013
Country           
B         100    0
A          20    0
C           0   40

Basically it gets the index of the sorted values and reindex the initial pivot table.

基本上它获取排序值的索引并重新索引初始数据透视表。