我有 2 个数据框,一个名为 USERS,另一个名为 EXCLUDE。他们都有一个名为“电子邮件”的字段。
基本上,我想删除 USERS 中包含 EXCLUDE 中的电子邮件的每一行。
我该怎么做?
最佳答案
您可以使用 boolean indexing
和条件 isin
, 反转 bool 值 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
关于python - 在 Pandas 中,如何从基于另一个数据框的数据框中删除行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39880627/