Python——按組大小對分組的 Pandas 資料框進行升序排序?


要對 Pandas 資料框進行分組,我們使用 groupby()。要對分組資料框按升序進行排序,請使用 sort_values()。size() 方法用於獲取資料框的大小。

對於升序排序,請在 sort_values() 中使用以下內容 −

ascending=True

首先,建立一個 Pandas 資料框 −

dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],

      "Reg_Price": [1000, 1400, 1000, 900, 1700, 900]
   }
)

然後,按照 Reg_Price 列進行分組並按升序排序 −

dataFrame.groupby('Reg_Price').size().sort_values(ascending=True)

示例

以下為程式碼 −

import pandas as pd

# dataframe with one of the columns as Reg_Price
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],

      "Reg_Price": [1000, 1400, 1000, 900, 1700, 900]
   }
)

print"DataFrame...\n",dataFrame

# group according to Reg_Price column and sort in ascending order
print"\nSorted in Ascending order...";
print(dataFrame.groupby('Reg_Price').size().sort_values(ascending=True))

輸出

這將產生以下輸出−

DataFrame...
        Car Reg_Price
0       BMW      1000
1     Lexus      1400
2      Audi      1000
3  Mercedes       900
4    Jaguar      1700
5   Bentley       900

Sorted in Ascending order...
Reg_Price
1400    1
1700    1
900     2
1000    2
dtype: int64

更新於:14-Sep-2021

474 次瀏覽

開啟您的 職業 生涯

透過完成本課程獲取認證

開始
廣告
© . All rights reserved.