0

I have two possible outcome values for a variable (returned from a function initialized as an empty list). It will either be a list of Pandas dataframes or [None]. How can I check this condition using if else?

I have tried,

if value[0]!=None and len(value)!=1:
    ....

I am getting the following error,

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

royalewithcheese
  • 402
  • 4
  • 17

1 Answers1

1

I would use all and isinstance:

if all(isinstance(x, pd.DataFrame) for x in values):
    # do something

Example:

values = [None]

if all(isinstance(x, pd.DataFrame) for x in values):
    print('Test1: OK')
    
values = [pd.DataFrame([]), pd.DataFrame([])]

if all(isinstance(x, pd.DataFrame) for x in values):
    print('Test2: OK')

Output:

Test2: OK

Note that your error is due to value[0] != None, you can fix it with:

if value[0] is not None and len(value)!=1:
    print('OK')
mozway
  • 194,879
  • 13
  • 39
  • 75
  • Thanks for your answer. Also how can I check whether two lists of dataframes are equal to each other or not? If I am using '==' to compare two lists of df's, I am getting the same error. – royalewithcheese Jul 04 '23 at 08:38
  • @royalewithcheese hard to answer without a reproducible example of the input to avoid ambiguity. `l1 == l2` does work to compare lists. – mozway Jul 04 '23 at 09:01
  • For instance, `import pandas as pd values_1 = [pd.DataFrame([]), pd.DataFrame([])] values_2 = [pd.DataFrame([]), pd.DataFrame([])] print(values_1==values_2)` – royalewithcheese Jul 04 '23 at 09:02
  • 1
    `all(x.equals(y) for x, y in zip(values_1, values_2))` – royalewithcheese Jul 04 '23 at 09:40