【问题标题】:Python combine map with groupby and transformPython将map与groupby和transform结合起来
【发布时间】:2020-04-22 20:03:05
【问题描述】:

我无法在 Python 中组合几个概念; groupby、映射和变换。我有一个数据框,我希望通过基于组转换现有列来创建新列。像这样:

s = df[df['type'].eq('office')].groupby(['user','date']).transform('any')
df.loc[:,'type2'] = df['type'].s.map({True:'office',False:'remote'})

所以我的数据框看起来像这样

user     date    type   type2
ron     12/1/19  office  office
ron     12/1/19  remote  office
april   12/1/19  office  office
leslie  12/1/19  remote  office
leslie  12/1/19  office  office
leslie  2/1/20   office  office

但我收到以下错误:

AttributeError: 'Series' object has no attribute 's'

我认为我已正确设置,但无法使其正常工作。感谢指导,谢谢

【问题讨论】:

  • df['type'].s 更改为 s?
  • @QuangHoang 当我这样做时,我得到AttributeError: 'DataFrame' object has no attribute 'map' 错误

标签: python pandas pandas-groupby transform


【解决方案1】:

修复你的代码

s = df['type'].eq('office').groupby([df['user'],df['date']]).transform('any')
df['type2'] = s.map({True:'office',False:'remote'})

【讨论】:

  • 这个编辑对我不起作用,第一行的 groupby 发生了一个 keyerror
  • 我不知道我可以像这样将 groupby 组合成多个列!你让我头疼不已,谢谢!
猜你喜欢
  • 2018-01-04
  • 1970-01-01
  • 2013-06-03
  • 1970-01-01
  • 2018-11-22
  • 2020-01-23
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
相关资源
最近更新 更多