[英]How to use numpy where on each element of test array without a for-loop?
I would like to use a numpy function in a routine without using a for-loop. 我想在例程中使用numpy函数而不使用for循环。 Consider the example below: 考虑下面的示例:
import numpy as np
data = np.linspace(1, 10, 10).astype(int)
test_elements = np.array([1, 2])
for test_elem in test_elements:
print(np.where(test_elem == data))
... ...
(array([0]),)
(array([1]),)
I've read other posts and the numpy documentation. 我读过其他文章和numpy文档。 Common suggestions seem to be using np.roll
to roll test_elements
, or using other tricks such as strides (which I do not completely understand). 常见的建议似乎是使用np.roll
滚动test_elements
,或使用其他技巧,例如大步迈进(我不完全理解)。 I thought it might be easier to use np.vectorize
to vectorize the function, but I have a feeling that this is overkill for a problem and that there must be a simpler solution. 我以为使用np.vectorize
对函数进行矢量化可能会更容易,但是我感觉这对于问题来说过于np.vectorize
过正,因此必须有一个更简单的解决方案。 Any guidance would be appreciated? 任何指导将不胜感激?
Here is one method using .outer
and np.split
I've made the example a bit more interesting. 这是使用.outer
和np.split
一种方法,我使示例变得更加有趣。
data = np.linspace(1, 5, 10).astype(int)
test_elements = np.array([1, 2, 4, 6])
y, x = np.where(np.equal.outer(test_elements,data))
np.split(x, y.searchsorted(np.arange(1,test_elements.size)))
# [array([0, 1, 2]), array([3, 4]), array([7, 8]), array([], dtype=int64)]
Some explanation: 一些解释:
np.equal.outer(test_elements,data)
is the same as 是相同的
test.elements[:,None] == data[None,:]
So this is a 2d boolean array whose rows equal the boolean arrays test_elem == data
occuring in your for loop. 因此,这是一个二test_elem == data
数组,其行等于for循环中出现的布尔数组test_elem == data
。
where
returns two index arrays from this, one for each coordinate. where
返回来自此两个食指的阵列,每一个坐标。 x
is the fast changing coordinate and is equal to the values the 1d where
of your for loop returns, but all glued together into one long vector. x
是瞬息万变的协调和等于值1D where
你for循环的回报,但都粘在一起成一个长的矢量。 y
is the slow chaning coordinate, it's values are ordered and can be used to group / split up x
. y
是慢速调整坐标,它的值是有序的,可以用于对x
进行分组/拆分。 searchsorted
may not be the most efficient way of doing that but it is simple and handles empty rows correctly. searchsorted
可能不是最有效的方法,但它很简单并且可以正确处理空行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.