【发布时间】:2017-02-14 07:00:06
【问题描述】:
我有 2 个数据框,一个名为 USERS,另一个名为 EXCLUDE。它们都有一个名为“email”的字段。
基本上,我想删除 USERS 中包含 EXCLUDE 中的电子邮件的每一行。
我该怎么做?
【问题讨论】:
我有 2 个数据框,一个名为 USERS,另一个名为 EXCLUDE。它们都有一个名为“email”的字段。
基本上,我想删除 USERS 中包含 EXCLUDE 中的电子邮件的每一行。
我该怎么做?
【问题讨论】:
您可以使用boolean indexing 和isin 的条件,反转布尔值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
【讨论】:
loc,它是通过带有布尔掩码的行和isin以及按列过滤 - 这里过滤列email
print (df[df._merge == 'left_only'])?
只是为了扩展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
【讨论】:
您还可以使用内部联接,获取 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
【讨论】:
我的解决方案就是找到共同的元素,提取共享密钥,然后使用该密钥将它们从原始数据中删除:
emails2remove = pd.merge(USERS, EXCLUDE, how='inner', on=['email'])['email']
USERS = USERS[ ~USERS['email'].isin(emails2remove) ]
【讨论】: