值数组在numpy数组中的位置 [英] location of array of values in numpy array
问题描述
这里有一个小代码来说明问题.
Here is a small code to illustrate the problem.
A = array([[1,2], [1,0], [5,3]])
f_of_A = f(A) # this is precomputed and expensive
values = array([[1,2], [1,0]])
# location of values in A
# if I just had 1d values I could use numpy.in1d here
indices = array([0, 1])
# example of operation type I need (recalculating f_of_A as needed is not an option)
f_of_A[ indices ]
因此,基本上我认为我需要一些与in1d等效的东西才能获得更高的尺寸.这样的事情存在吗?还是有其他方法?
So, basically I think I need some equivalent to in1d for higher dimensions. Does such a thing exist? Or is there some other approach?
好像还有一个searchsorted()函数,但这似乎也适用于一维数组.在此示例中,我使用了2d点,但是任何解决方案也需要适用于3d点.
Looks like there is also a searchsorted() function, but that seems to work for 1d arrays also. In this example I used 2d points, but any solution would need to work for 3d points also.
推荐答案
好的,这就是我想出的.
Okay, this is what I came up with.
要找到一个多维索引的值,例如ii = np.array([1,2])
,我们可以执行以下操作:
To find the value of one multi-dimensional index, let's say ii = np.array([1,2])
, we can do:
n.where((A == ii).all(axis=1))[0]
让我们分解一下,我们有了A == ii
,它将对A
的每一行与ii
进行逐元素比较.我们希望整行都是真实的,因此我们添加.all(axis=1)
使其折叠.为了找到这些索引发生的位置,我们将其插入np.where
并获取元组的第一个值.
Let's break this down, we have A == ii
, which will give element-wise comparisons with ii
for each row of A
. We want an entire row to be true, so we add .all(axis=1)
to collapse them. To find where these indices happen, we plug this into np.where
and get the first value of the tuple.
现在,我还没有一种快速的方法来处理多个索引(尽管我有一种感觉).但是,这可以完成工作:
Now, I don't have a fast way to do this with multiple indices yet (although I have a feeling there is one). However, this will get the job done:
np.hstack([np.where((A == values[i]).all(axis=1))[0] for i in xrange(len(values))])
对于每个values
值,这基本上只是调用上述方法,并将结果串联起来.
This basically just calls the above, for each value of values
, and concatenates the result.
更新:
这里是多维案例(一口气,应该相当快):
Here is for the multi-dimensional case (all in one go, should be fairly fast):
np.where((np.expand_dims(A, -1) == values.T).all(axis=1).any(axis=1))[0]
这篇关于值数组在numpy数组中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!