【问题标题】:pandas create boolean column using groupby transform熊猫使用 groupby 变换创建布尔列
【发布时间】: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。我想知道发生了什么,我需要pandaspython 3 的更新吗?

更新

pandas 更新为0.22.0 修复了此问题。

【问题讨论】:

  • 你为什么用groupby
  • @WillemVanOnsem 觉得很方便
  • 方便完成什么任务?
  • 我在 pandas 0.21.10.22.0 中测试它工作正常,所以尝试升级 pandas。
  • @jezrael 将pandas 更新为0.22.0,问题现已修复,谢谢

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    使用这条线

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

    为我工作:)

    【讨论】:

      猜你喜欢
      • 2018-03-17
      • 2019-04-12
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      • 1970-01-01
      • 2019-07-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多