【问题标题】:Sort the order of dataframe columns based on the values in the bottom row根据底行中的值对数据框列的顺序进行排序
【发布时间】:2019-01-18 16:18:42
【问题描述】:

我试过了,但它不起作用:

df5[[c for c in sorted(list(df5.columns), key=df5.iloc[-1].get, reverse=True)]]

【问题讨论】:

  • 请参阅如何制作MCVE。在这种情况下,我想我已经根据您的示例代码理解了您在寻找什么,并希望我能回答它。我试图澄清标题。

标签: python pandas numpy dataframe


【解决方案1】:

你很亲密。试试这个:

import pandas as pd

df = pd.DataFrame({'a': [1, 2, 3], 'b': [ 4, 5, 2], 'c': [2, 4, 5]})
print(df)

df = df[[x for _, x in sorted(zip(df.iloc[-1], df.columns), reverse=True)]]
print(df)

开始数据帧:

   a  b  c
0  1  4  2
1  2  5  4
2  3  2  5

按底行中的值降序排列的列:

  c  a  b
0  2  1  4
1  4  2  5
2  5  3  2

【讨论】:

    【解决方案2】:

    试试这个:

    import pandas as pd
    data = pd.read_csv('your_data_file')
    sort_column = data.sort_values('name_of_column',ascending=False)
    print(sort_column)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      • 2012-09-03
      • 2020-06-18
      • 1970-01-01
      • 2020-08-04
      • 2021-09-23
      相关资源
      最近更新 更多