首页 > 解决方案 > 如何根据最小到最大值组织熊猫数据框列?

问题描述

所以我有一些代码可以导入一个示例 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]

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

标签: pythonpandasdataframeindexing

解决方案


我认为您需要DataFrame.sort_values使用[]forSeries然后进行选择Series.to_frame

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

您的解决方案由DataFrame.sort_valueswith更改,用于按索引值axis=1排序:i

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

推荐阅读