Skip to main content
 首页 » 编程设计

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

2025年05月04日12jirigala

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)。