I have 2 Data Frames, one named USERS and another named EXCLUDE. Both of them have a field named “email”.
Basically, I want to remove every row in USERS that has an email contained in EXCLUDE.
How can I do it?
Advertisement
Answer
You can use boolean indexing
and condition with isin
, inverting boolean Series
is by ~
:
JavaScript
x
17
17
1
import pandas as pd
2
3
USERS = pd.DataFrame({'email':['a@g.com','b@g.com','b@g.com','c@g.com','d@g.com']})
4
print (USERS)
5
email
6
0 a@g.com
7
1 b@g.com
8
2 b@g.com
9
3 c@g.com
10
4 d@g.com
11
12
EXCLUDE = pd.DataFrame({'email':['a@g.com','d@g.com']})
13
print (EXCLUDE)
14
email
15
0 a@g.com
16
1 d@g.com
17
JavaScript
1
22
22
1
print (USERS.email.isin(EXCLUDE.email))
2
0 True
3
1 False
4
2 False
5
3 False
6
4 True
7
Name: email, dtype: bool
8
9
print (~USERS.email.isin(EXCLUDE.email))
10
0 False
11
1 True
12
2 True
13
3 True
14
4 False
15
Name: email, dtype: bool
16
17
print (USERS[~USERS.email.isin(EXCLUDE.email)])
18
email
19
1 b@g.com
20
2 b@g.com
21
3 c@g.com
22
Another solution with merge
:
JavaScript
1
15
15
1
df = pd.merge(USERS, EXCLUDE, how='outer', indicator=True)
2
print (df)
3
email _merge
4
0 a@g.com both
5
1 b@g.com left_only
6
2 b@g.com left_only
7
3 c@g.com left_only
8
4 d@g.com both
9
10
print (df.loc[df._merge == 'left_only', ['email']])
11
email
12
1 b@g.com
13
2 b@g.com
14
3 c@g.com
15