在 Pandas 中,如何从基于另一个数据帧的数据帧中删除行? [英] In Pandas, how to delete rows from a Data Frame based on another Data Frame?
本文介绍了在 Pandas 中,如何从基于另一个数据帧的数据帧中删除行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 2 个数据帧,一个名为 USERS,另一个名为 EXCLUDE.他们都有一个名为email"的字段.
I have 2 Data Frames, one named USERS and another named EXCLUDE. Both of them have a field named "email".
基本上,我想删除 USERS 中包含在 EXCLUDE 中的电子邮件的每一行.
Basically, I want to remove every row in USERS that has an email contained in EXCLUDE.
我该怎么做?
推荐答案
您可以使用 boolean 索引
和条件 isin
,反转布尔值 Series
是由 ~
:
You can use boolean indexing
and condition with isin
, inverting boolean Series
is by ~
:
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
<小时>
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
这篇关于在 Pandas 中,如何从基于另一个数据帧的数据帧中删除行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文