简体   繁体   中英

Python Pandas find value in dataframe regardless of column

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.

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')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM