如何将布尔数组转换为numpy中的索引数组 [英] How to turn a boolean array into index array in numpy

查看:290
本文介绍了如何将布尔数组转换为numpy中的索引数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相对于布尔型掩码数组,是否存在一种有效的Numpy机制来根据条件为true检索数组中位置的整数索引?

Is there an efficient Numpy mechanism to retrieve the integer indexes of locations in an array based on a condition is true as opposed to the Boolean mask array?

例如:

x=np.array([range(100,1,-1)])
#generate a mask to find all values that are a power of 2
mask=x&(x-1)==0
#This will tell me those values
print x[mask]

在这种情况下,我想知道mask的索引i,其中mask[i]==True.是否可以生成这些而不循环?

In this case, I'd like to know the indexes i of mask where mask[i]==True. Is it possible to generate these without looping?

推荐答案

另一个选项:

In [13]: numpy.where(mask)
Out[13]: (array([36, 68, 84, 92, 96, 98]),)

numpy.where(mask==True)相同.

这篇关于如何将布尔数组转换为numpy中的索引数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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