【问题标题】:Create a new column based on conditional count of other column grouped by id根据 id 分组的其他列的条件计数创建一个新列
【发布时间】:2022-01-21 04:35:33
【问题描述】:

我有一个这样的数据框: 我的目标是计算按 id 分组的国家的数量,但仅限于(美国、加拿大、墨西哥)

id country desired_output
a usa 1
b canada 2
b canada 2
c china 0
d mexico 3
d mexico 3
d mexico 3

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: python pandas dataframe count pandas-groupby


【解决方案1】:

Series.whereSeries.isin 中将id 或其他列转换为NaN,然后通过GroupBy.transformGroupBy.count 计算非NaNs 行:

L = ["usa","canada","mexico"]
df['desired_output'] = df.id.where(df.country.isin(L)).groupby(df['id']).transform('count')
print (df)
  id country  desired_output
0  a     usa               1
1  b  canada               2
2  b  canada               2
3  c   china               0
4  d  mexico               3
5  d  mexico               3
6  d  mexico               3

【讨论】:

    猜你喜欢
    • 2020-08-18
    • 1970-01-01
    • 2017-08-26
    • 2020-06-02
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多