Pandas 使用组内的多个条件检查值是否存在,如果为真则计算值

Pandas check if a value exists using multiple conditions within group and count value if true

我已经根据我确定的条件创建了一个布尔值列。我想更进一步,计算每组的真值。

我有

group = df.groupby('id')
df.loc[:,'Match'] = (group['flag'].transform(lambda x: x.eq(0).any()))&(group['flag'].transform(lambda x: x.eq(1).any()))

这给了我 True 和 False 值。然后我如何计算每个 ID 填充的真值的数量?

示例数据:

id   flag   Match  Count Match
123  0      True    3
123  1      True    3
123  1      True    3
567  0      False   0
567  0      False   0

上面创建了Match列,那我要创建Count Match列。

是吗:

df['Count Match'] = df['Match'].astype(int).groupby(df['id']).transform('sum')