如何根据最小值到最大值来组织pandas数据帧列



所以我有一些导入示例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))]

然后,它组织起来,使每一行都成为一个新的数据帧,并带有一个看起来像的out

[         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]

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

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

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

我认为您需要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))]

相关内容

最新更新