【问题标题】:Remove the duplicate values when the status is changing for same id当相同 id 的状态发生变化时删除重复值
【发布时间】:2021-07-09 22:13:18
【问题描述】:

我想删除规则显示 NOT_OK 的行,而对于一个值,它对于同一个 id 已经OK。

而对于一个id,如果所有的值都是NOT_OK,那么就保留所有的值。

例如,对于这个数据集:

ID RULE
1   OK
1   NOT_OK
2   NOT_OK
2   NOT_OK

期望的输出:

ID RULE
1    OK
2   NOT_OK
2   NOT_OK

【问题讨论】:

    标签: python pandas duplicates conditional-statements


    【解决方案1】:

    假设您的数据集是变量“df”中的数据框。可能有一种更有效的方法,但这很有效:

    ok_records = list(df['ID'][df['RULE'] == 'OK'])
    df1 = df[(df['ID'].isin(ok_records)) & (df['RULE'] != 'NOT_OK')]
    df2 = df[(df['RULE'] == 'NOT_OK') & (~df['ID'].isin(ok_records))]
    final_df = pd.concat([df1, df2])
    

    【讨论】:

    • final_df 应该为您提供问题中所述的所需输出。
    【解决方案2】:

    删除重复功能应该可以工作:https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop_duplicates.html

    只要df.drop_duplicates()

    【讨论】:

    • 不,它不起作用。至于 id 1 有 OK 和 NOT OK。在那种情况下,我只想保持 OK,而在 id 2 中没有 OK。我想保持两者都不好。状态
    猜你喜欢
    • 1970-01-01
    • 2020-10-21
    • 2022-07-15
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多