adam.hendry
adam.hendry

Reputation: 5673

How Do You Check if an Entry Is in Pandas DataFrame?

How do I check if an entry is in a pandas DataFrame? For example, say

import pandas as pd

df = pd.DataFrame({'A' : [1,2,3], 'B' : [4,5,6], 'C' : [7,8,9]})

How do I check if the entry 1,4 exists in an entry under columns A,B, regardless of what is in C?

Upvotes: 0

Views: 894

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61930

You can pass a dictionary (to isin) with the values to search by column:

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
result = df.isin({'A': [1], 'B': [4]})
print(result)

Output

       A      B
0   True   True
1  False  False
2  False  False

Afterwards you can find if the entry exists using all:

result = df.isin({'A': [1], 'B': [4]}).all(1)
print(result)

Output

0     True
1    False
2    False
dtype: bool

To use it in an if statement, and just on the columns ['A', 'B'], use any, for example:

if df[['A', 'B']].isin({'A': [1], 'B': [4]}).all(1).any():
    print('found')

Upvotes: 1

Related Questions