python - 在数据框中使用 isin 和 NaN

标签 python pandas

假设我有以下数据框:

    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 使用 numpynan 定义

[2] 正如 @root 指出的,这是依赖于 dtype 的。

关于python - 在数据框中使用 isin 和 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57188795/

相关文章:

python - 值错误: How to iterate through a tuple of Boolean True/False statements?

python - Pandas 中返回数字而不是书籍的按位运算?

python和pandas绘制两个日期索引值之间的图

python - 将字符串从 pandas 数据帧转换为列表 - python

python - 条件打印输入

python - Bigfloat - 精度错误

python - subprocess.check_output 返回码

python - pandas 根据日期时间条件删除行

python - pandas 中行之间的减法 - python

python - Django 窗口函数