Python: check if value appears anywhere in a list of dataframes

Question:

I have a variable var = myString and a list of dataframes dfList. Each dataframe in the list is two columns of strings df = pd.DataFrame({'col1': ['x','y','z'], 'col2': ['a','myString','b']}). If var appears anywhere in any dataframe in the list I need to execute a series of functions. I could check by looping through each dataframe in the list, but I am hoping for a method of checking that I can easily incorporate into part of a one line elif statement.

Asked By: keenan

||

Answers:

Try this.

import pandas as pd

var = 'myString'

df = pd.DataFrame({'col1': ['x','y','z'], 'col2': ['a','myString','b']})



mystringIN = any((df[a] == var).any() for a in df.columns)


print(mystringIN)

Output

True
Answered By: codester_09

Starting with this solution, to find if a value is present in a DataFrame, we can extend it to a list of dataframes as:

True in [df.isin([var]).any().any() for df in dfList]

Which will be True if var is present, False otherwise.

It works whether var is a string or any other type.

Answered By: Ignatius Reilly