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:
This entry was posted in Python and tagged . Bookmark the permalink.

3 Responses to Pandas : how to compare dataframe with None

  1. Anonymous says:

    This doesn’t to seem work anymore.

    • Hi, could be that pandas has evolved and this code is obsolet. without example, will be difficult to help you further, consider asking pandas developers, or dedicated website such as stackoverflow.com
      best

  2. Anonymous says:

    Thanks a lot. Also didn’t RTFM.

Leave a Reply

Your email address will not be published.