python - 在 Pandas 中,如何从基于另一个数据框的数据框中删除行?

标签 python pandas merge

我有 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/

相关文章:

python - makedirs 给出 OSError : [Errno 13] Permission denied: '/pdf_files'

python-2.7 - 如何在 python seaborn 热图旁边有一个栏来显示行值的总和?

python-3.x - 无法逆转 pandas 数据帧中的第一个差异

python - 计算相关矩阵子集的最快方法

video - ffmpeg:连接视频并与一个音频合并

svn - 通过多次合并跟踪 SVN 更改

python - 将列表作为嵌套列表,在单独列表中包含连续元素

python - 线程1 :EXC_BAD_INSTRACTION

python - Pandas:将宽数据框 reshape 为多索引长数据框

python - pandas:在不同类型的列上连接两个数据框