【问题标题】:In Pandas, how to delete rows from a Data Frame based on another Data Frame?在 Pandas 中,如何根据另一个 Data Frame 从 Data Frame 中删除行?
【发布时间】:2017-02-14 07:00:06
【问题描述】:

我有 2 个数据框,一个名为 USERS,另一个名为 EXCLUDE。它们都有一个名为“email”的字段。

基本上,我想删除 USERS 中包含 EXCLUDE 中的电子邮件的每一行。

我该怎么做?

【问题讨论】:

    标签: python pandas merge


    【解决方案1】:

    您可以使用boolean indexingisin 的条件,反转布尔值Series~

    import pandas as pd
    
    USERS = pd.DataFrame({'email':['a@g.com','b@g.com','b@g.com','c@g.com','d@g.com']})
    print (USERS)
         email
    0  a@g.com
    1  b@g.com
    2  b@g.com
    3  c@g.com
    4  d@g.com
    
    EXCLUDE = pd.DataFrame({'email':['a@g.com','d@g.com']})
    print (EXCLUDE)
         email
    0  a@g.com
    1  d@g.com
    
    print (USERS.email.isin(EXCLUDE.email))
    0     True
    1    False
    2    False
    3    False
    4     True
    Name: email, dtype: bool
    
    print (~USERS.email.isin(EXCLUDE.email))
    0    False
    1     True
    2     True
    3     True
    4    False
    Name: email, dtype: bool
    
    print (USERS[~USERS.email.isin(EXCLUDE.email)])
         email
    1  b@g.com
    2  b@g.com
    3  c@g.com
    

    merge 的另一个解决方案:

    df = pd.merge(USERS, EXCLUDE, how='outer', indicator=True)
    print (df)
         email     _merge
    0  a@g.com       both
    1  b@g.com  left_only
    2  b@g.com  left_only
    3  c@g.com  left_only
    4  d@g.com       both
    
    print (df.loc[df._merge == 'left_only', ['email']])
         email
    1  b@g.com
    2  b@g.com
    3  c@g.com
    

    【讨论】:

    • 嗨,Jezrael,您能解释一下第二种解决方案中的 ix 是什么:(df.ix[df._merge == 'left_only', ['email']])。谢谢!
    • @user8322222 - 这是旧代码,现在可以使用loc,它是通过带有布尔掩码的行和isin以及按列过滤 - 这里过滤列email
    • 感谢耶斯瑞尔!我有一个与此类似的问题,除了我想最后保留两个数据框的列。如果您有时间,希望您能提供意见:
    • @user8322222 - 所以需要print (df[df._merge == 'left_only'])
    • 你已经在评论它了哈哈:stackoverflow.com/questions/54219055/…
    【解决方案2】:

    只是为了扩展jezrael 的答案,可以使用相同的方法来根据多列过滤行。

    USERS = pd.DataFrame({"email": ["a@g.com", "b@g.com", "c@g.com", 
                                    "d@g.com", "e@g.com"],
                          "name": ["a", "s", "d", 
                                   "f", "g"],
                          "nutrient_of_choice": ["pizza", "corn", "bread", 
                                                 "coffee", "sausage"]})
    
    print(USERS)    
    
         email name nutrient_of_choice
    0  a@g.com    a              pizza
    1  b@g.com    s               corn
    2  c@g.com    d              bread
    3  d@g.com    f             coffee
    4  e@g.com    g            sausage
    
    EXCLUDE = pd.DataFrame({"email":["x@g.com", "d@g.com"],
                            "name": ["a", "f"]})
    
    print(EXCLUDE)
    
         email name
    0  x@g.com    a
    1  d@g.com    f
    

    现在,假设我们只想过滤具有匹配名称和电子邮件的行:

    USERS = pd.merge(USERS, EXCLUDE, on=["email", "name"], how="outer", indicator=True)
    
    print(USERS)
    
         email name nutrient_of_choice      _merge
    0  a@g.com    a              pizza   left_only
    1  b@g.com    s               corn   left_only
    2  c@g.com    d              bread   left_only
    3  d@g.com    f             coffee        both
    4  e@g.com    g            sausage   left_only
    5  x@g.com    a                NaN  right_only
    
    USERS = USERS.loc[USERS["_merge"] == "left_only"].drop("_merge", axis=1)
    
    print(USERS)
    
         email name nutrient_of_choice
    0  a@g.com    a              pizza
    1  b@g.com    s               corn
    2  c@g.com    d              bread
    4  e@g.com    g            sausage
    

    【讨论】:

      【解决方案3】:

      您还可以使用内部联接,获取 USERS 中包含电子邮件 EXCLUDE 的索引或行,然后从 USERS 中删除它们。下面我使用@jezrael 示例来展示这一点:

      import pandas as pd
      USERS = pd.DataFrame({'email': ['a@g.com',
                                      'b@g.com',
                                      'b@g.com',
                                      'c@g.com',
                                      'd@g.com']})
      
      EXCLUDE = pd.DataFrame({'email':['a@g.com',
                                       'd@g.com']})
      
      # rows in USERS and EXCLUDE with the same email
      duplicates = pd.merge(USERS, EXCLUDE, how='inner',
                        left_on=['email'], right_on=['email'],
                        left_index=True)
      
      # drop the indices from USERS
      USERS = USERS.drop(duplicates.index)
      

      这个回报:

      USERS
          email
      2   b@g.com
      3   c@g.com
      4   d@g.com
      

      【讨论】:

        【解决方案4】:

        我的解决方案就是找到共同的元素,提取共享密钥,然后使用该密钥将它们从原始数据中删除:

        emails2remove = pd.merge(USERS, EXCLUDE, how='inner', on=['email'])['email']
        USERS = USERS[ ~USERS['email'].isin(emails2remove) ]
        

        【讨论】:

          猜你喜欢
          • 2023-02-05
          • 2021-11-09
          • 2022-12-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-02
          • 2021-01-11
          • 1970-01-01
          相关资源
          最近更新 更多