我的应用程序需要比较有时包含nan的Series实例。这导致使用==
进行普通比较失败,因为nan != nan
:
import numpy as np
from pandas import Series
s1 = Series([1,np.nan])
s2 = Series([1,np.nan])
>>> (Series([1, nan]) == Series([1, nan])).all()
False
比较此类系列的正确方法是什么?
这个怎么样。首先检查NaN是否在同一位置(使用isull):
In [11]: s1.isnull()
Out[11]:
0 False
1 True
dtype: bool
In [12]: s1.isnull() == s2.isnull()
Out[12]:
0 True
1 True
dtype: bool
然后检查不是NaN的值相等(使用notnull):
In [13]: s1[s1.notnull()]
Out[13]:
0 1
dtype: float64
In [14]: s1[s1.notnull()] == s2[s2.notnull()]
Out[14]:
0 True
dtype: bool
为了平等,我们都必须为真:
In [15]: (s1.isnull() == s2.isnull()).all() and (s1[s1.notnull()] == s2[s2.notnull()]).all()
Out[15]: True
如果还不够,还可以检查名称等。
如果你想提高,如果它们是不同的,使用assert_series_equal
来自pandas.util.testing
:
In [21]: from pandas.util.testing import assert_series_equal
In [22]: assert_series_equal(s1, s2)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句