pandas 比较熊猫系列在包含 nan 时是否相等?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/18453442/
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
Comparing pandas Series for equality when they contain nan?
提问by Dun Peal
My application needs to compare Series instances that sometimes contain nans. That causes ordinary comparison using ==to fail, since nan != nan:
我的应用程序需要比较有时包含 nan 的系列实例。这会导致普通比较使用==失败,因为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
What's the proper way to compare such Series?
比较此类系列的正确方法是什么?
回答by Andy Hayden
How about this. First check the NaNs are in the same place (using isnull):
这个怎么样。首先检查 NaN 是否在同一个地方(使用isnull):
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
Then check the values which aren't NaN are equal (using notnull):
然后检查不是 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 order to be equal we need both to be True:
为了相等,我们需要两者都为真:
In [15]: (s1.isnull() == s2.isnull()).all() and (s1[s1.notnull()] == s2[s2.notnull()]).all()
Out[15]: True
You could also check name etc. if this wasn't sufficient.
如果这还不够,您还可以检查名称等。
If you want to raiseif they are different, use assert_series_equalfrom pandas.util.testing:
如果您想提高它们是否不同,请使用assert_series_equalfrom pandas.util.testing:
In [21]: from pandas.util.testing import assert_series_equal
In [22]: assert_series_equal(s1, s2)
回答by Sam
回答by Jeff
In [16]: s1 = Series([1,np.nan])
In [17]: s2 = Series([1,np.nan])
In [18]: (s1.dropna()==s2.dropna()).all()
Out[18]: True

