Skip to main content
 首页 » 编程设计

python之特定值在 groupby 中计数

2025年05月04日13arxive

我有以下数据框:

df = pd.DataFrame([ 
    ('A', 'A', 'Cat'), 
    ('A', 'A', 'Dog'), 
    ('A', 'A', 'Cat'), 
    ('A', 'B', 'Dog'), 
    ('B', 'B', 'Rat'), 
    ('B', 'C', 'Cat'), 
    ('B', 'C', 'Cat') 
], columns=['id', 'group', 'Animal']) 

我想按 id 和 group 对其进行分组,并计算每个组中 Cat 的出现次数。示例输出将是:

[2, 0, 0, 2] 

AA 组中的 2 cat,

AB 组中的 0 cat,

BB 组中的 0 cat,

BC 组中的 2 cat

有人可以帮忙吗?谢谢!

请您参考如下方法:

你需要mask + groupby:

df['Animal'] = df['Animal'].mask(df['Animal'].ne('Cat')) 
df.groupby(['id', 'group'])['Animal'].count().tolist() 

[2, 0, 0, 2]