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
  1. import pandas as pd
  2. import numpy as np
  3. # set seed
  4. set_random = np.random.RandomState(123)
  5. length =6
  6. dates = pd.date_range('1/1/2000', periods=length)
  7. df_sample = pd.DataFrame(np.round(set_random.uniform(1,2,(length,2)) ), index=dates, columns=['A', 'B'])
  8. df_sample
  9. print('before sort')
  10. print(df_sample)
  11. print('after sort ascending')
  12. df_sample = df_sample.sort_values(by=['A','B'],ascending=True)
  13. print(df_sample)
  14. print('after sort descending')
  15. df_sample = df_sample.sort_values(by=['A','B'],ascending=False)
  16. 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

沒有留言:

張貼留言