我有来自 panda 数据透视表的数据,看起来像这样:
df:
sum
PrctChange
Year 2011 2012 2013 2014 2015
CountryName
Argentina 17.378744 5.750719 7.923327 -0.062792 8.889681
Belize 0.515086 -1.278683 16.819298 -0.104759 10.539688
Burundi 0.000000 inf 3.209646 2.165577 6.411365
我正在尝试按 2015 年的数据对其进行排序,以便将其列为伯利兹、阿根廷和布隆迪(2015 年的值按降序排列)
我见过一些非常相关和相似的问题,但它们似乎对我不起作用
From this question ,我试过:
pivot_sorted = df_values(('PrctChange', 2015))
得到这个错误:
KeyError: ('PrctChange', 2015)
From this question ,我试过:
pivot_sorted = df.sortlevel(["2015"], ascending=[False], sort_remaining=False)
我没有收到错误,但没有排序。
最后,我尝试了这个
pivot_sorted = df.sort_values(by=(df['2015']), ascending=False,inplace=True)
得到这个错误:
KeyError: '2015'
有人可以帮忙吗?谢谢!
最佳答案
列是一个三层多索引对象。您必须使用所有三个级别来选择一列。
df.sort_values(('sum', 'PrctChange', '2015'), ascending=False)
关于python - Panda Pivot - 按列排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42917442/