假设我有以下数据:
df=pd.DataFrame({"id":[1,1,1,2,2,3,4],
"date":[2019,2019,2020,2020,2020,2020,2021],
"subgroup":["con","ind","ind","con","ind","ind","ind"],
"value":[1,None,2,None,1,3,4]})
我想按照ID和日期分组,然后在那些重复项中,获取一个列,该列根据Subgroup列中的值(在此情况下,当Subgroup ==“Ind”时)计算Value列中缺失值的数量。 输出如下:
id date subgroup value count
1 2019 con 1 1
1 2019 ind None 1
1 2020 ind 2 0
2 2020 con None 0
2 2020 ind 1 0
3 2020 ind 3 0
4 2021 ind 4 0
我该如何实现这个目标?
df['count'] = (df['value'].isnull() & df['subgroup'].eq('ind')).groupby([df['id'], df['date']]).transform('sum')
- ALollz