如何根据最小到最大值组织熊猫数据框列?

时间:2021-01-06 04:03:27

标签: python pandas dataframe indexing

所以我有一些导入示例 csv 文件的代码:

 import pandas as pd
import numpy as np

df = pd.read_csv('/Users/benitocano/Downloads/airtravel.csv')
df.columns = ['Month', '1', '2', '3']

df.set_index('Month', inplace=True)
count = 0
for i in df.index:
    d = pd.DataFrame()
    d = df.iloc[[count]]
    count = count + 1

[df.iloc[[i]] for i in range(len(df))]

然后组织起来使每一行成为一个新的数据框,输出如下所示:

[         1    2  3
 Month             
 JAN    360  417  0,
          1    2  3
 Month             
 FEB    342  391  1,
          1    2  3
 Month             
 MAR    406  419  2,
          1    2  3
 Month             
 APR    396  461  3,
          1    2  3
 Month             
 MAY    420  472  4,
          1    2  3
 Month             
 JUN    472  535  5,
          1    2  3
 Month             
 JUL    548  622  6,
          1    2  3
 Month             
 AUG    559  606  7,
          1    2  3
 Month             
 SEP    463  508  8,
          1    2  3
 Month             
 OCT    407  461  9,
          1    2   3
 Month              
 NOV    362  390  10,
          1    2   3
 Month              
 DEC    405  432  11]

我的问题是如何对每个数据框的列进行排序,以便它们的值从小到大排列?

2 个答案:

答案 0 :(得分:1)

我认为您需要 DataFrame.sort_values 选择 []Series,然后选择 Series.to_frame

[df.loc[i].sort_values(i).to_frame() for i in df.index]

您的解决方案由 DataFrame.sort_values 更改为 axis=1 以按 i 索引值排序:

[df.iloc[[i]].sort_values(by=df.index[i], axis=1) for i in range(len(df))]

答案 1 :(得分:1)

您可以通过以下方式更改最后一行代码:

[df.loc[[i]].sort_values(by = i, axis = 1) for i in df.index]