python - pandas 使用 groupby 变换创建 bool 列

标签 python python-3.x pandas pandas-groupby

我正在尝试在 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。我想知道发生了什么事,我需要更新 pandaspython 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/

相关文章:

python - 如何创建具有特定重复模式 1 和 0 的二进制矩阵?

python - tensorflow : "trying to mutate a frozen object",巴泽尔

python - 使用递归函数时避免字符串+整数相加

python - 在python中组合两个字符串

python - 获取 DataFrame 列作为值列表

python - Pandas 数据框根据其他数据框的列创建一个新列

python - 流式传输大型 csv 文件的最快方法是什么?

python - 如何正确索引二维数组 pandas dataframe?

python-3.x - AWS Patch Manager 在 Ubuntu 22.04 上失败

python - 如何 reshape 多个时间序列信号以与 sns.tsplot 一起使用?