Skip to content
Advertisement

Search for a value anywhere in a pandas DataFrame

This seems like a simple question, but I couldn’t find it asked before (this and this are close but the answers aren’t great).

The question is: if I want to search for a value somewhere in my df (I don’t know which column it’s in) and return all rows with a match.

What’s the most Pandaic way to do it? Is there anything better than:

for col in list(df):
    try:    
        df[col] == var
        return df[df[col] == var]
    except TypeError:
        continue 

?

Advertisement

Answer

You can perform equality comparison on the entire DataFrame:

df[df.eq(var1).any(1)]
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement