pandas 使用 groupby 转换创建布尔列 [英] pandas create boolean column using groupby transform

查看:42
本文介绍了 pandas 使用 groupby 转换创建布尔列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在这样的 df 上使用 GroupBy.transform 创建一个布尔列,

I am trying to create a boolean column using GroupBy.transform on a df like this,

id    type
1     1.00000
1     1.00000
2     2.00000
2     3.00000
3     2.00000

代码就像,

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

但不是布尔值,has_two 具有浮点值,例如0.0.我想知道为什么会这样.

but instead of boolean values, has_two has float values, e.g. 0.0. I am wondering why is that.

更新

我创建了一个测试用例,

I created a test case,

df = pd.DataFrame({'id':['1', '1', '2', '2', '3'], 'type':[1.0, 1.0, 2.0, 1.0, 2.0]})
df['has_2'] = df.groupby('id')['type'].transform(lambda x: x == 2)

这给了我,

   id  type  has_2
0  1   1.0    0.0
1  1   1.0    0.0
2  2   2.0    1.0
3  2   1.0    0.0
4  3   2.0    1.0

如果我按照 jezrael 的建议使用 df['has_2'] = df['type'] == 2,那就没问题了,

if I am using df['has_2'] = df['type'] == 2 as suggested by jezrael, it is fine,

   id  type  has_2
0  1   1.0  False
1  1   1.0  False
2  2   2.0   True
3  2   1.0  False
4  3   2.0   True

我在 Python 3.5.2 上使用 pandas==0.20.3.我想知道发生了什么,我需要更新 pandaspython 3 吗?

I am using pandas==0.20.3 on Python 3.5.2. I am wondering what's going on, do I need an update on pandas or python 3?

更新

pandas 更新到 0.22.0 修复了这个问题.

Updated pandas to 0.22.0 fixed this issue.

推荐答案

对我来说它工作得很好,我得到布尔列:

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

但也许只能比较列:

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

这篇关于 pandas 使用 groupby 转换创建布尔列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆