Python Pandas find value in dataframe regardless of column

Viewed 653

Is there a simple way to check for a value within a dataframe when it could possibly be in a variety of columns? Whether using iterrow and searching each row for the value and finding which column it is in or just checking the dataframe as a whole and getting its position like iat coords.

2 Answers

You can search the value in dataframe and get the Boolean dataframe for your search. It gives you all equalities of var1 in df.

df[df.eq(var1).any(1)]
import pandas as pd
d = {'id': [1, 2, 3], 'col2': [3, 4, 5], 'col3': [8,3,9]}
df = pd.DataFrame(data=d)
df = df.set_index('id')
df

Sample Data

    col2    col3
id      
1   3   8
2   4   3
3   5   9

Find 3

df.isin([3]).any()

Output Column:

col2    True
col3    True
dtype: bool

Want more detals? Here you go:

df[df.isin([3])].stack().index.tolist()

Co-ordinates output:

[(1, 'col2'), (2, 'col3')]
Related