python - Panda Pivot - 按列排序

标签 python pandas pivot

我有来自 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/

相关文章:

sql - APEX 5 ORACLE SQL 中的动态魔法枢轴错误 "Only simple column names allowed here"

python - Django mongoengine 文档中的 Manytomany 字段

Python Not - 将参数传递给命令处理程序

相当于 Python 的参数化 string.format() 函数的 JavaScript

python - 使用 read_xml 将数据从两个 XML 父节点导入到 Pandas DataFrame

Mysql 对旋转或转置值的计数

SQL Server 多枢轴

python - 我同时安装了 python 2.7 和 3.5,但是 python 3.5 不能正常工作

python - 创建新的 DataFrame 作为其他 DataFrame 列的有序组合

python - 为什么在提供 int 系列时 pd.to_timedelta 会失败?