How to compare pandas DataFrame against None in Python?

CiaranWelsh picture CiaranWelsh · Mar 25, 2016 · Viewed 18.6k times · Source

How do I compare a pandas DataFrame with None? I have a constructor that takes one of a parameter_file or a pandas_df but never both.

def __init__(self,copasi_file,row_to_insert=0,parameter_file=None,pandas_df=None):
    self.copasi_file=copasi_file
    self.parameter_file=parameter_file
    self.pandas_df=pandas_df      

However, when I later try to compare the pandas_df against None, (i.e. when self.pandas_df actually contains a pandas dataframe):

    if self.pandas_df!=None:
        print 'Do stuff'

I get the following TypeError:

  File "C:\Anaconda1\lib\site-packages\pandas\core\internals.py", line 885, in eval
    % repr(other))

TypeError: Could not compare [None] with block values

Answer

Mike Müller picture Mike Müller · Mar 25, 2016

Use is not:

if self.pandas_df is not None:
    print 'Do stuff'

PEP 8 says:

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

There is also a nice explanation why.