【问题标题】:How to apply conditions on lines that have the same ID如何在具有相同 ID 的行上应用条件
【发布时间】:2020-07-03 21:42:24
【问题描述】:

我有一个像这样的数据框:

df= [ ID  child_ID  STATUS1  
      123  11        OK    
      123  22        KO 
      123  23        OK 
      124  56        OK  
      124  45        OK

我想通过 ID 获得最终状态,如果其中一个 childid 是 KO,则意味着我的最终状态是 KO,所以我想要一个类似的数据框:

f= [      ID  Child_ID  STATUS1  Statusfinal
          123  11           OK       KO
          123  22           KO       KO
          123  23           OK       KO
          124  56           OK       OK
          124  45           OK       OK 

我该怎么做?

【问题讨论】:

    标签: python pandas numpy dataframe group-by


    【解决方案1】:

    我会先计算一个额外的布尔列,然后使用 groupby 聚合:

    resul = df.assign(FinalStatus = ((df['STATUS1'].str.lower() == 'ok') &
                      (df['STATUS2'].str.lower() == 'ok'))
              ).groupby('ID').agg({'STATUS1': 'first',
                       'STATUS2': 'first',
                       'FinalStatus': all}).reset_index()
    

    在最后一列添加正确的标签,仅此而已:

    resul['FinalStatus'] = np.where(resul['FinalStatus'], 'OK', 'KO')
    

    给予:

       ID STATUS1 STATUS2 FinalStatus
    0  12      OK      OK          KO
    1  13      OK      OK          OK
    

    【讨论】:

    • 当我尝试你的方式时,我在最后一个命令中遇到错误:ValueError:值的长度与索引的长度不匹配
    • 我猜不出你的数据到底是什么。请提供minimal reproducible example,以便我重现。
    • 我设法只有一个状态可以检查,所以我改变了我的问题,希望你有答案!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 2022-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多