我正在尝试在 df
上使用 GroupBy.transform
创建一个 bool 列,如下所示,
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
不是 bool 值,而是浮点值,例如0.0
。我想知道为什么会这样。
更新
我创建了一个测试用例,
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
,那就没问题了,
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
。我想知道发生了什么事,我需要更新 pandas
或 python 3
吗?
更新
将 pandas
更新为 0.22.0
修复了此问题。
最佳答案
对我来说它工作得很好,我得到 bool 列:
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
关于python - pandas 使用 groupby 变换创建 bool 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48059985/