pandas create boolean column using groupby transform

◇◆丶佛笑我妖孽 提交于 2019-12-06 06:10:10

For me it working nice, I get boolean column:

df['has_two'] = df.groupby('id')['type'].transform(lambda x: x == 2)
print (df)
   id  type  has_two
0   1   1.0    False
1   1   1.0    False
2   2   2.0     True
3   2   3.0    False
4   3   2.0     True

But maybe is possible only compare column:

df['has_two'] = df['type'] == 2
print (df)
   id  type  has_two
0   1   1.0    False
1   1   1.0    False
2   2   2.0     True
3   2   3.0    False
4   3   2.0     True

Use this line

df['has_two'] = df.groupby('id')['type'].transform(lambda x: x == 2) == 2

Worked for me :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!