【问题标题】:overwriting the column rows basis the condition根据条件覆盖列行
【发布时间】:2022-11-18 20:01:15
【问题描述】:

现有数据框:

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

预期数据框:

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:condition1 == 'attempt' & condition2 =='pass'。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    你可以试试:

    m1 = df['condition1'].eq('attempt')
    m2 = df['condition2'].eq('pass')
    
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      相关资源
      最近更新 更多