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
Active
Viewed 38 times
0

keenan
- 462
- 3
- 12
-
and your Question is? – The Singularity Sep 28 '22 at 02:40
-
Is there a way I can check if var appears in any dataframe in the list of dataframes as part of a one line if statement? – keenan Sep 28 '22 at 02:42
-
Does the `var` always occur in `col2`? – The Singularity Sep 28 '22 at 02:42
-
no it could be in either column – keenan Sep 28 '22 at 02:43
2 Answers
0
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

codester_09
- 5,622
- 2
- 5
- 27
0
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.

Ignatius Reilly
- 1,594
- 2
- 6
- 15