如何从 numpy 数组中快速获取特定索引?

How to quickly grab specific indices from a numpy array?

但是我没有索引值,我只有在不同数组中的相同索引中的索引值。例如,我有

a = array([3,4,5,6])
b = array([0,1,0,1])

是否有一些 NumPy 方法可以快速查看这两者并从 a 中提取所有值,其索引与 [=17] 中所有 1 的索引相匹配=]?我希望它产生:

array([4,6])

可能值得一提的是,我的 a 数组是多维的,而我的 b 数组的值始终为 01。我尝试使用 NumPylogical_and 函数,尽管此 returns ValueErrorab 具有不同的维度:

a = numpy.array([[3,2], [4,5], [6,1]])
b = numpy.array([0, 1, 0])
print numpy.logical_and(a,b)

ValueError: operands could not be broadcast together with shapes (3,2) (3,) 

尽管如果 a 平坦,此方法似乎确实有效。无论哪种方式,numpy.logical_and() 的 return 类型都是布尔值,这是我不想要的。还有别的办法吗?同样,在上面的第二个示例中,所需的 return 将是

array([[4,5]])

显然我可以写一个简单的循环来完成这个,我只是在寻找更简洁的东西。

编辑:

这会引入更多的约束,我还应该提到多维数组的每个元素 a 可以是任意长度,与其相邻元素不匹配。

您可以简单地使用花哨的索引。

b == 1

会给你一个布尔数组:

>>> from numpy import array
>>> a = array([3,4,5,6])
>>> b = array([0,1,0,1])
>>> b==1
array([False,  True, False,  True], dtype=bool)

您可以将其作为索引传递给 a.

>>> a[b==1]
array([4, 6])

第二个示例的演示:

>>> a = array([[3,2], [4,5], [6,1]])
>>> b = array([0, 1, 0])
>>> a[b==1]
array([[4, 5]])

你可以使用 compress:

>>> a = np.array([3,4,5,6])
>>> b = np.array([0,1,0,1])
>>> a.compress(b)
array([4, 6])

您可以为多维案例提供 axis 参数:

>>> a2 = np.array([[3,2], [4,5], [6,1]])
>>> b2 = np.array([0, 1, 0])
>>> a2.compress(b2, axis=0)
array([[4, 5]])

即使您索引的 a 的轴与 b 的长度不同,此方法也有效。