Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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  

?

like image 231
Josh Friedlander Avatar asked Dec 30 '18 16:12

Josh Friedlander


People also ask

How do I find a particular value in a pandas DataFrame column?

You can check if a column contains/exists a particular value (string/int), list of multiple values in pandas DataFrame by using pd. series() , in operator, pandas. series. isin() , str.

How do I search for a specific cell in pandas?

In Pandas, DataFrame. loc[] property is used to get a specific cell value by row & label name(column name).

How do you check if a value is in a series pandas?

isin() function check whether values are contained in Series. It returns a boolean Series showing whether each element in the Series matches an element in the passed sequence of values exactly.


2 Answers

You can perform equality comparison on the entire DataFrame:

df[df.eq(var1).any(1)] 
like image 67
cs95 Avatar answered Sep 19 '22 15:09

cs95


You should using isin , this is return the column , is want row check cold' answer :-)

df.isin(['bal1']).any() A        False B         True C        False CLASS    False dtype: bool 

Or

df[df.isin(['bal1'])].stack() # level 0 index is row index , level 1 index is columns which contain that value  0  B    bal1 1  B    bal1 dtype: object 
like image 44
BENY Avatar answered Sep 21 '22 15:09

BENY