在Python Pandas和Numpy中,比较结果为何不同?
from pandas import Series
from numpy import NaN
NaN
不等于NaN
>>> NaN == NaN
False
但是列表或元组中的
NaN
是>>> [NaN] == [NaN], (NaN,) == (NaN,)
(True, True)
虽然
Series
与NaN
再次不相等:>>> Series([NaN]) == Series([NaN])
0 False
dtype: bool
和
None
:>>> None == None, [None] == [None]
(True, True)
尽管
>>> Series([None]) == Series([None])
0 False
dtype: bool
This answer总体上解释了
NaN == NaN
成为False
的原因,但未解释其在python/pandas集合中的行为。 最佳答案
如here和here以及python docs中所述,以检查序列是否相等
因为np.nan
和np.NaN
指向同一个对象,即(np.nan is np.nan is np.NaN) == True
,所以该等式保存[np.nan] == [np.nan]
,但是另一方面float('nan')
函数在每次调用时都会创建一个新对象,因此[float('nan')] == [float('nan')]
是False
。
Pandas/Numpy没有这个问题:
>>> pd.Series([np.NaN]).eq(pd.Series([np.NaN]))[0], (pd.Series([np.NaN]) == pd.Series([np.NaN]))[0]
(False, False)
尽管特殊的equals方法将相同位置的
NaN
视为相等。>>> pd.Series([np.NaN]).equals(pd.Series([np.NaN]))
True
None
的处理方式有所不同。 numpy
认为它们相等:>>> pd.Series([None, None]).values == (pd.Series([None, None])).values
array([ True, True])
虽然
pandas
不>>> pd.Series([None, None]) == (pd.Series([None, None]))
0 False
1 False
dtype: bool
==
运算符和eq
方法之间也存在不一致之处,这在here中进行了讨论:>>> pd.Series([None, None]).eq(pd.Series([None, None]))
0 True
1 True
dtype: bool
在
pandas: 0.23.4 numpy: 1.15.0
上测试关于python - Pandas/Numpy NaN无比较,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52436356/