2017年7月7日 星期五

Python - How to sort a dataFrame in python pandas by two or more columns - 如何在pandas dataframe使用兩個或兩個以上的column排序資料

Python版本:Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
Pandas版本:0.19.2
系統版本:Windows 10
import pandas as pd
import numpy as np
# set seed
set_random = np.random.RandomState(123)
length =6
dates = pd.date_range('1/1/2000', periods=length)
df_sample = pd.DataFrame(np.round(set_random.uniform(1,2,(length,2)) ), index=dates, columns=['A', 'B'])
df_sample

print('before sort')
print(df_sample)

print('after sort ascending')
df_sample = df_sample.sort_values(by=['A','B'],ascending=True)
print(df_sample)

print('after sort descending')
df_sample = df_sample.sort_values(by=['A','B'],ascending=False)
print(df_sample)
執行結果:

before sort
              A    B
2000-01-01  2.0  1.0
2000-01-02  1.0  2.0
2000-01-03  2.0  1.0
2000-01-04  2.0  2.0
2000-01-05  1.0  1.0
2000-01-06  1.0  2.0
after sort ascending
              A    B
2000-01-05  1.0  1.0
2000-01-02  1.0  2.0
2000-01-06  1.0  2.0
2000-01-01  2.0  1.0
2000-01-03  2.0  1.0
2000-01-04  2.0  2.0
after sort descending
              A    B
2000-01-04  2.0  2.0
2000-01-01  2.0  1.0
2000-01-03  2.0  1.0
2000-01-02  1.0  2.0
2000-01-06  1.0  2.0
2000-01-05  1.0  1.0

沒有留言:

張貼留言