创建一个布尔数组,将 numpy 元素与 None 进行比较 [英] creating a boolean array which compares numpy elements to None

查看:26
本文介绍了创建一个布尔数组,将 numpy 元素与 None 进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 dtype=object 的 numpy 数组,我想创建一个布尔数组来标识哪些元素是 None.但看起来 None 的行为有所不同...

I have a numpy array with dtype=object, and I want to create a boolean array identifying which elements are None. But it looks like None behaves differently...

a = np.array(['Duck','Duck','Duck','Goose',None,1,2,3,1,3,None,4])
print a == 'Duck'
print a == 3
print a == None

导致

[ True  True  True False False False False False False False False False]
[False False False False False False False  True False  True False False]
False

是否有一种numpythonic"方法来获取 None 元素的布尔数组?我可以使用

Is there an "numpythonic" way to get a boolean array of the None elements? I can use

np.array([x is None for x in a])

但这似乎应该有更好的方法.

but this seems like there should be a better way.

推荐答案

您可以使用 numpy.equal:

You can use numpy.equal:

In [20]: np.equal(a, None)
Out[20]: 
array([False, False, False, False,  True, False, False, False, False,
       False,  True, False], dtype=bool)

这篇关于创建一个布尔数组,将 numpy 元素与 None 进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆