【发布时间】:2018-01-02 11:16:58
【问题描述】:
我正在尝试像这样在 df 上使用 GroupBy.transform 创建一个布尔列,
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。我想知道为什么会这样。
更新
我创建了一个测试用例,
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 修复了此问题。
【问题讨论】:
-
你为什么用
groupby? -
@WillemVanOnsem 觉得很方便
-
方便完成什么任务?
-
我在 pandas
0.21.1和0.22.0中测试它工作正常,所以尝试升级 pandas。 -
@jezrael 将
pandas更新为0.22.0,问题现已修复,谢谢
标签: python python-3.x pandas pandas-groupby