Python - 按组大小降序排列分组的 Pandas 数据框?
要分组 Pandas 数据框,我们使用 groupby()。要按降序对分组的数据框进行排序,请使用 sort_values()。size() 方法用于获取数据框大小。
对于降序排序,在 sort_values() 中使用以下内容 -
ascending=False
首先,创建一个 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=False)
示例
以下是代码
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 descending order
print"\nSorted in Descending order...";
print(dataFrame.groupby('Reg_Price').size().sort_values(ascending=False))输出
这将生成以下输出 -
DataFrame...
Car Reg_Price
0 BMW 1000
1 Lexus 1400
2 Audi 1000
3 Mercedes 900
4 Jaguar 1700
5 Bentley 900
Sorted in Descending order...
Reg_Price
1000 2
900 2
1700 1
1400 1
dtype: int64
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP