python - 使用对象 dtype 的 ndarray 与 None 进行元素比较

标签 python arrays numpy

x = np.empty([2], dtype=object)
> array([None, None], dtype=object)

x[0] = 'a'
> array(['a', None], dtype=object)

我试图从这个类型为 ndarray 的对象中获取一个 bool 数组 [False, True],其中对象类型为 None

不起作用的东西:x is None, x.isfinite(), x == None, np .isnan(x)。该数组可能有 n 维度,使得 for 循环迭代看起来不愉快。

最佳答案

在 NumPy 1.12 及更早版本中,您需要显式调用 numpy.equal 以获得广播相等性比较。发表评论,以便 future 的读者了解您这样做的原因:

# Comparisons to None with == don't broadcast (yet, as of NumPy 1.12).
# We need to use numpy.equal explicitly.
numpy.equal(x, None)

在 NumPy 1.13 及更高版本中,x == None will give you a broadcasted equality comparison , 但如果你想向后兼容早期版本,你仍然可以使用 numpy.equal(x, None)

关于python - 使用对象 dtype 的 ndarray 与 None 进行元素比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44295919/

相关文章:

python - 使用 python 中的请求循环分页 REST API

python - 仅返回使用 PyGithub 的问题

python - 如何制作跨列具有一致网格的分组条形图?

python - 在 Python 中拥有唯一标识符的正确方法?

java - 从特定列索引开始遍历数组

c - 2 个关于 typedef 结构和平均成绩的问题。我在 C 中做得正确吗?

python - 使用 x,y,z 排序将 1D numpy 数组 reshape 为 3D

java - 在 Java 中将 PDF 添加到一起

python - Python中一定距离内去重

c++ - NumPy 的 C++ : How to iterate over PyArrayObject without a segfault