Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 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 Reply

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...