如何對 Pandas DataFrame 的多列進行排序?


要對 Pandas DataFrame 的多列進行排序,我們可以使用 sort_values() 方法。

步驟

  • 建立一個二維、大小可變、潛在異構表格資料 df

  • 列印輸入 DataFrame df

  • 初始化變數 col 來對該列進行排序。

  • 列印已排序的 DataFrame。

示例

 現場演示

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 7, 0],
      "y": [4, 7, 5, 1],
      "z": [9, 3, 5, 1]
   }
)
print "Input DataFrame is:
", df col = ["x", "y"] df = df.sort_values(col, ascending=[False, True]) print "After sorting column ", col, "DataFrame is:
", df

輸出結果

Input DataFrame is:
   x  y  z
0  5  4  9
1  2  7  3
2  7  5  5
3  0  1  1

After sorting column ['x', 'y'] DataFrame is:
   x  y  z
2  7  5  5
0  5  4  9
1  2  7  3
3  0  1  1

更新日期:2021 年 8 月 30 日

898 次瀏覽

開啟您的 事業

完成課程認證

開始學習
廣告
© . All rights reserved.