【发布时间】:2021-10-25 01:28:54
【问题描述】:
我有以下数据框
import pandas as pd
country = ['US', 'US', 'US', 'UK', 'UK', 'Canada', 'Canada', "Mexico"]
feature = [2, 2, 2, 1, 1, 2, 2, 1]
ID = [1, 2, 1, 3, 4, 1, 2, 1]
df = pd.DataFrame(list(zip(country,feature, ID)),
columns =['country', 'feature', 'ID'])
这是
country feature ID
0 US 2 1
1 US 2 2
2 US 2 1
3 UK 1 3
4 UK 1 4
5 Canada 2 1
6 Canada 2 2
7 Mexico 1 1
鉴于上述数据框,我想在 country 上执行 groupby。我想使用以下规则为每个country 创建一个值count:如果feature ==2,count = number of unique entries under ID for that country。如果feature !=2,count = number of total entries for that country。因此,生成的新数据框将如下所示:
country count
0 US 2
1 UK 2
2 Canada 2
3 Mexico 1
【问题讨论】:
-
为什么是加拿大1?
-
如果某些国家/地区同时拥有
feature == 2和feature != 2怎么办?
标签: python pandas dataframe conditional-statements pandas-groupby