Pandas : how to compare dataframe with None

While comparing a pandas dataframe with None,

import pandas as pd
df = pd.DataFrame() # Note that the dataframe is empty but it does not matter for this example.
if df == None:
    pass # do nothing
else:
   df.describe()

I got this error:

ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().

I could go around the problen using the isinstance command:

import pandas as pd
df = pd.DataFrame() # Note that the dataframe is empty but it does not matter for this example.
if isinstance(df, types.NoneType) == True:
#equivalent to if isinstance(df, pd.DataFrame) == False    
    pass # do nothing
else:
   df.describe()

In fact, the first code could be changed just slightly by replacing the comparison operator with the is keyword:

if df is None:
    pass # do nothing
else:
   df.describe()

I could have spared some time by looking carefully into the Pandas documentation

Please follow and like us:
error
This entry was posted in Python and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published.