gpt4 book ai didi

python - Pandas pivot_table,按列对值进行排序

转载 作者:太空狗 更新时间:2023-10-29 18:26:10 25 4
gpt4 key购买 nike

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

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

我附上了一张来自 Excel 的图片,因为它更容易以表格格式显示我想要实现的目标。 Link to image

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

提前致谢

最佳答案

这应该可以满足您的需求:

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

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

关于python - Pandas pivot_table,按列对值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41119623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com