Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

python - How to organize pandas dataframe columns based on smallest to greatest values?

So I have some code that imports a sample csv file:

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

It then organizes to make each individual row a new dataframe, with an out that looks like:

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

My question is how do I order each dataframes' columns so that their values are arranged smallest to greatest?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can change your last code line by:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...