Python Pandas "groupby" 和 "if any" 条件

9

我有一个类似于以下数据框的数据,我想创建一个新变量,如果每个项目中至少覆盖了 "a" 部门,则该变量包含 true/false。 我尝试使用 group.by() 函数,并希望使用 .transform() 方法,但由于我的数据是文本,我不知道如何使用它。

      project    sector  
    
        01         a    
        01         b    
        02         b     
        02         b     
        03         a     
        03         a     
    



 project    sector   new_col

    01         a     true
    01         b     true
    02         b     false
    02         b     false
    03         a     true
    03         a     true

       
2个回答

4
你可以尝试以下方法:
df['new_col'] = df.groupby('project')['sector'].transform(lambda x: (x == 'a').any() )

这将按项目分组,并检查“a”是否在该组的部门中。


2

这可能不是最快的选择,但绝对能够正常工作。

new_col = your_db.groupby(['project'])['sector'].unique().apply(lambda x: 'a' in x).rename('new_col')
your_db = your_db.merge(new_col, how = 'inner', left_on = 'project', right_on = 'project')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接