Pandas 分组 - 统计每个组合的出现次数
若要按列分组并统计 Pandas 中每个组合出现的次数,我们将使用 DataFrame.groupby() 和 size()。groupby() 方法将 DataFrame 分成不同的组。
首先,让我们导入熊猫库并用 pd 设置别名 -
import pandas as pd
初始化列表数据 -
# initializing the data
mylist = {'Car': ['BMW', 'Mercedes', 'Lamborgini', 'Audi', 'Mercedes', 'Porche', 'RollsRoyce', 'BMW'], 'Place': ['Delhi', 'Hyderabad', 'Chandigarh', 'Bangalore', 'Hyderabad', 'Mumbai', 'Mumbai','Delhi'],
'Sold': [95, 80, 80, 75, 90, 90, 95, 50 ]}接下来,我们将创建 DataFrame -
# DataFrame dataFrame = pd.DataFrame(mylist, columns=['Car', 'Place', 'Sold'])
现在,使用 groupby() 并用 size() 统计出现次数 -
print("Counting the occurrences...")
res = dataFrame.groupby(['Car', 'Place']).size()以下是统计每个组合出现次数的代码 -
示例
# importing library
import pandas as pd
# initializing the data
mylist = {'Car': ['BMW', 'Mercedes', 'Lamborgini', 'Audi', 'Mercedes', 'Porsche', 'RollsRoyce', 'BMW'],
'Place': ['Delhi', 'Hyderabad', 'Chandigarh', 'Bangalore', 'Hyderabad', 'Mumbai', 'Mumbai','Delhi'],
'Sold': [95, 80, 80, 75, 90, 90, 95, 50 ]}
# DataFrame
dataFrame = pd.DataFrame(mylist, columns=['Car', 'Place', 'Sold'])
print(dataFrame)
print("Counting the occurrences...")
res = dataFrame.groupby(['Car', 'Place']).size()
# Displaying the occurrences
print(res)输出
将生成以下输出 -
Car Place Sold 0 BMW Delhi 95 1 Mercedes Hyderabad 80 2 Lamborgini Chandigarh 80 3 Audi Bangalore 75 4 Mercedes Hyderabad 90 5 Porsche Mumbai 90 6 RollsRoyce Mumbai 95 7 BMW Delhi 50 Counting the occurrences... Car Place Audi Bangalore 1 BMW Delhi 2 Lamborgini Chandigarh 1 Mercedes Hyderabad 2 Porsche Mumbai 1 RollsRoyce Mumbai 1 dtype: int64
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP