Python结合map与groupby和transform

问题描述 投票:0回答:1

在Python中,我在组合几个概念时遇到了问题:groupby、map和transform。 我有一个数据框架,我想通过基于一个组来转换一个现有的列来创建一个新的列。像这样。

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'

我以为我设置得很正确,但却无法正常工作。感谢指导,谢谢

python pandas pandas-groupby transform
1个回答
1
投票

修正你的代码

s = df['type'].eq('office').groupby([df['user'],df['date']]).transform('any')
df['type2'] = s.map({True:'office',False:'remote'})
© www.soinside.com 2019 - 2024. All rights reserved.