Skip to main content
 首页 » 编程设计

python之pandas 使用 groupby 转换创建 bool 列

2024年09月07日9zfyouxi

我正在尝试在 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) 

但不是 bool 值,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 修复了这个问题。

请您参考如下方法:

对我来说它工作得很好,我得到了 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