但我没有索引值,我只有在不同数组中的相同索引中的索引值。例如,我有
a = array([3,4,5,6])
b = array([0,1,0,1])
有没有NumPy
方法可以快速查看这两个值并从 a
中提取所有值其索引匹配所有 1
的索引在 b
中?我希望它产生:
array([4,6])
可能值得一提的是我的 a
数组是多维的,而我的 b
array 的值总是 0
或 1
.我尝试使用 NumPy
的 logical_and
函数,尽管这会返回 ValueError
与 a
和 b
具有不同的维度:
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()
的返回类型是一个 bool 值,我不想要。还有别的办法吗?同样,在上面的第二个例子中,期望的返回是
array([[4,5]])
显然我可以写一个简单的循环来完成这个,我只是在寻找更简洁的东西。
编辑:
这会引入更多的约束,我还应该提到多维数组的每个元素 a
可以是任意长度,与其邻居不匹配。
最佳答案
您可以简单地使用花哨的索引。
b == 1
会给你一个 bool 数组:
>>> 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]])
关于python - 如何从 numpy 数组中快速获取特定索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34343630/