简体   繁体   English

使用索引数组将值分配给numpy中的数组

[英]Using an index array to assign values to an array in numpy

I am trying to vectorize this operation to speed up run time. 我正在尝试向量化此操作以加快运行时间。 To set up my problem look at the following code. 要设置我的问题,请看以下代码。

current_array=np.array([[2,3],[5,6],[34,0]])
ind =np.array([[0,1],[1,1],[0,0]])
new_vals=[99,77]

##do some magic
result = [[99,77],[77,77],[99,99]]

So we have the current array and I want to use the values in ind to assign the values of new_vals to current_array such that you end up with result. 因此,我们有了当前数组,我想使用ind中的值将new_vals的值分配给current_array ,以便最终得到结果。

I have a way to do this but it uses two loops and I would like to speed it up as much as possible. 我有办法做到这一点,但它使用了两个循环,我想尽可能地加快速度。 Right now I am doing the following 现在我正在做以下

def set_image_vals(image,means,mins):
    for i in range(0,image.shape[0]):
        for j in range(0,image.shape[1]):
            image[i,j]=means[mins[i,j]]
    return image

where image would be current_array , means would be new_vals and mins would be ind. 其中image为current_array ,意味着为new_vals ,mins为ind。

Is there a better way to do this that can speed things up? 有没有更好的方法可以加快速度?

For the general case, this is the most flexible and fastest: 对于一般情况,这是最灵活,最快的:

>>> new_vals = np.array([99, 77])
>>> new_vals[ind]
array([[99, 77],
   [77, 77],
   [99, 99]])

Here, new_vals could have more than two elements, and ind can index up to that number of elements. 在这里, new_vals可以包含两个以上的元素,并且ind可以索引多达该数量的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM