pandas 根据条件覆盖列行

vohkndzv  于 2022-11-20  发布在  其他
关注(0)|答案(1)|浏览(167)

现有数据框架:

Id           condition1        condition2       score
A               attempt           pass            0
A               attempt           fail            0
B               attempt           pass            0
B               attempt           level_1         0
B               attempt           fail            0
C               attempt           fail            0
D               attempt           fail            0

预期的 Dataframe :

Id           condition1        condition2       score
A               attempt           pass            1
A               attempt           fail            1
B               attempt           pass            1
B               attempt           level_1         1
B               attempt           fail            1
C               attempt           fail            0
D               attempt           fail            0

如果满足以下任何一行的条件,我希望将唯一ID的每行中的分数标记为1:条件1 ==“尝试”&条件2 ==“通过”。

zaqlnxep

zaqlnxep1#

您可以尝试:

m1 = df['condition1'].eq('attempt')
m2 = df['condition2'].eq('pass') | df['condition2'].eq('level_1')

df['score'] = (m1 & m2)
df['score'] = df.groupby('Id')['score'].transform(lambda x: x.any().astype(int))

  Id condition1 condition2  score
0  A    attempt       pass      1
1  A    attempt       fail      1
2  B    attempt       pass      1
3  B    attempt    level_1      1
4  B    attempt       fail      1
5  C    attempt       fail      0
6  D    attempt       fail      0

相关问题