Pandas 单击groupby并指示列是否具有特定值
有很多类似的问题,但没有一个能完全解决我的问题 我有一个用户和位置的数据框架。用户可以有多个位置。我想转换数据,以便每个用户在列中有一个位置。为此,我想检查一个用户是否将“纽约”作为一个位置,否则会将“其他”作为一个位置 因此,user1值:Pandas 单击groupby并指示列是否具有特定值,pandas,dataframe,pandas-groupby,Pandas,Dataframe,Pandas Groupby,有很多类似的问题,但没有一个能完全解决我的问题 我有一个用户和位置的数据框架。用户可以有多个位置。我想转换数据,以便每个用户在列中有一个位置。为此,我想检查一个用户是否将“纽约”作为一个位置,否则会将“其他”作为一个位置 因此,user1值: user1 : New York user1 : Boston 输出为: user 1: New York user 1: New York user2: Other user2: Other 然后是user2值: user2: B
user1 : New York
user1 : Boston
输出为:
user 1: New York
user 1: New York
user2: Other
user2: Other
然后是user2值:
user2: Boston
user2: San Fran
输出为:
user 1: New York
user 1: New York
user2: Other
user2: Other
我试过这个:
group_by_user = sample['office_type'].groupby(sample['user'])
sample.loc[:,'office_type2'] = ['New York' if ele == 'New York' else 'Other' for ele in sample['office_type']]
但这不会在两行中填充“纽约”,而是填充:
user1: New York
user1: Other
我想让它填充
user1: New York
user1: New York
IIUC让我们使用
any
执行转换
,它将groupby
用户检查是否有任何纽约,如果有,对于所有行,用户返回True
s=sample['office_type'].eq('New York').groupby(sample['user']).transform('any')
sample.loc[:,'office_type']=s.map({True:'New York', False: 'Other'} )
太好了,谢谢!此结构对我以后的转换有很大帮助(不要忘记下次格式化=)