This was done quite a while ago to make the behavior of nulls consistent, in that they don't compare equal. This puts None and np.nan on an equal (though not-consistent with python, BUT consistent with numpy) footing.
Comparisons to singletons like None should always be done with is or is not, never the equality operators.
例如,您可以执行tst.value.apply(lambda x: x is None),这会产生与.isnull()相同的结果,说明pandas如何将它们视为NaNs。注意这是下面的tst数据帧示例,其中tst.value.dtypes是一个object,我已经显式指定了NoneType元素。你知道吗
如上注释所述,
pandas
中缺少的数据由NaN表示,其中NaN是一个数值,即浮点类型。但是None是PythonNoneType
,因此NaN将不等价于None。你知道吗在此Github thread中,他们进一步讨论,指出:
这意味着当你做
df[df['label'] == None]
,你要elementwise
检查np.nan == np.nan
,我们知道是假的。你知道吗此外,在应用Boolean indexing时,不应执行
df[df['label'] == None]
,对NoneType
使用==
不是最佳实践,正如PEP8所述:例如,您可以执行
tst.value.apply(lambda x: x is None)
,这会产生与.isnull()
相同的结果,说明pandas
如何将它们视为NaNs。注意这是下面的tst
数据帧示例,其中tst.value.dtypes
是一个object
,我已经显式指定了NoneType
元素。你知道吗在
pandas
文档中有一个很好的example说明了这一点及其效果。你知道吗例如,如果您有两个列,一个是
float
类型,另一个是object
,您可以看到pandas如何以一种很好的方式处理None
类型,请注意float
它使用的是NaN。你知道吗这篇文章很好地解释了NaN和None之间的区别,肯定会看看这个。你知道吗
相关问题 更多 >
编程相关推荐