假设我有以下数据框:
t2 t5
0 NaN 2.0
1 2.0 NaN
2 3.0 1.0
现在我想检查 t2
中的元素是否在 t5
中,忽略 NaN
。
因此,我运行以下代码:
df['t2'].isin(df['t5'])
这给出:
0 True
1 True
2 False
但是,由于 NaN!=NaN
,我预计
0 False
1 True
2 False
如何获得我所期望的结果?为什么会这样?
最佳答案
这并不是一个错误,而是类似库之间的行为不一致。您的列的数据类型为 float64
,并且 Pandas 和 Numpy 对于 nan
是否与 nan
相当有自己的想法 [1].您可以通过 unique
>>> np.unique([np.nan, np.nan])
array([nan, nan])
>>> pd.unique([np.nan, np.nan])
array([nan])
很明显,pandas
检测到了与 nan
的某种相似性,这就是您在 isin
中看到的行为。
现在,对于大型系列,您不会看到此行为[2]。我想我在某处读到截止值约为 10e6,但不要相信我的话。
u = pd.Series(np.full(100000000, np.nan, dtype=np.float64))
>>> u.isin(u).any()
False
[1] 对于大型系列 (> 10e6),pandas
使用 numpy
的 nan
定义
[2] 正如 @root 指出的,这是依赖于 dtype
的。
关于python - 在数据框中使用 isin 和 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57188795/