如何在 Python 中将 Pandas DataFrame 与 None 进行比较?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36217969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:55:57  来源:igfitidea点击:

How to compare pandas DataFrame against None in Python?

pythonpandaspython-2.xnonetype

提问by CiaranWelsh

How do I compare a pandas DataFrame with None? I have a constructor that takes one of a parameter_fileor a pandas_dfbut never both.

如何将 Pandas DataFrame 与None? 我有一个构造函数,它采用 aparameter_file或 a之一,pandas_df但从不采用两者。

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_dfagainst None, (i.e. when self.pandas_dfactually contains a pandas dataframe):

但是,当我稍后尝试比较pandas_dfNone, 时(即self.pandas_df实际包含Pandas数据框时):

    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

回答by Mike Müller

Use is not:

使用is not

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

PEP 8says:

PEP 8说:

Comparisons to singletons like Noneshould always be done with isor is not, never the equality operators.

与单例的比较None应该总是用isor来完成is not,而不是等号运算符。

There is also a nice explanationwhy.

还有一个很好的解释为什么。