【问题标题】:Delete rows based on multiple conditions in different columns / Python Pandas根据不同列中的多个条件删除行/ Python Pandas
【发布时间】:2021-09-06 02:13:39
【问题描述】:

我的第一篇文章。我希望我能够正确地提出这个问题。 在下面的df中有需要根据多个条件删除的行。

所有行,其中“ID”存在(可能是一次或多次)并且都显示“confTyp” == “new” & “trType == “order” & Version == 1 表示这些是有效条目。

现在,如果“ID”不是唯一的,并且具有相同“ID”的行之一显示“confTyp”!=new 或“trTyp”!=“order”。需要删除具有相同“ID”的所有行。这也意味着必须删除带有假定正确的“confTyp”、“trTyp2”和“Version”的初始“ID”。

删除任何 != "new" 仍然会留下原始条目,然后也必须将其删除。

我已经以许多不同的方式尝试了 df.drop() 方法,但我远不是一个好的解决方案。有谁知道什么方法合适?

感谢您的帮助。

我有以下数据框:

ID confTyp trType Version
100 new order 1
101 new order 1
102 new order 1
103 new order 1
104 new order 1
105 new order 1
106 new order 1
107 replace manual 1
106 cancel cancel 2
106 replace manual 1
105 replace replace 2
104 cancel cancel 2
108 new order 1

目标是以下输出:

ID confTyp trType Version
100 new order 1
101 new order 1
102 new order 1
103 new order 1
108 new order 1

【问题讨论】:

  • 使用df[~df["ID"].duplicated(keep=False)]获取唯一ID。

标签: python pandas multiple-conditions drop


【解决方案1】:

IIUC,你可以试试:

df = df.set_index('ID')[df.groupby('ID').apply(lambda x:  all([set(x['confTyp']) == {
    'new'}, set(x['trType']) == {'order'}, set(x['Version']) == {1}]))]

输出:

   confTyp trType  Version
ID                         
100     new  order        1
101     new  order        1
102     new  order        1
103     new  order        1
108     new  order        1

【讨论】:

  • 这段代码对我有用。非常感谢。也感谢其他人。我也会尝试其他的。太棒了
【解决方案2】:

IIUC,你想要这样的东西(假设 ID 是你的 DataFrame df 的索引):

output = pd.DataFrame()
for ID in df.index.unique():
    sample = df[df.index==ID]
    if sample.shape[0] > 1 and any(sample["confTyp"]!="new") and any(sample["trType"]!="order"):
        continue
    if not (all(sample["confTyp"]=="new") and all(sample["trType"]=="order") and all(sample["Version"]==1)):
        continue
    output = output.append(sample)

>>> output
    confTyp trType  Version
ID                         
100     new  order        1
101     new  order        1
102     new  order        1
103     new  order        1
108     new  order        1

【讨论】:

    【解决方案3】:

    您可以找到与条件不匹配的ID并通过它们过滤原始DataFrame

    ids = df.loc[(df.confTyp != 'new') | (df.trType != 'order') | (df.Version != 1)].ID
    df = df[~df.ID.isin(ids)]
    
    ID   confTyp trType  Version
    100  new     order   1
    101  new     order   1
    102  new     order   1
    103  new     order   1
    108  new     order   1
    

    【讨论】:

      猜你喜欢
      • 2018-06-12
      • 2022-06-21
      • 1970-01-01
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多