Function to return a copy of np.array with replaced elements

I have a Numpy array and a list of indexes, as well as an array with the values ​​that need to be entered into these indexes.

The fastest way I know how to achieve this:

In [1]: a1 = np.array([1,2,3,4,5,6,7])

In [2]: x = np.array([10,11,12])

In [3]: ind = np.array([2,4,5])

In [4]: a2 = np.copy(a1)

In [5]: a2.put(ind,x)

In [6]: a2
Out[6]: array([ 1,  2, 10,  4, 11, 12,  7])

Please note that I had to make a copy a1. I use this to wrap a function that takes an array as input, so I can give it to an optimizer that will vary some of these elements.

So, ideally, I would like to have something that returns a modified copy of the original in one line, which works as follows:

a2 = np.replace(a1, ind, x)

The reason for this is that I need to apply it like this:

def somefunction(a):
    ....

costfun = lambda x: somefunction(np.replace(a1, ind, x))

With a constant a1and ind, which then will give me a cost function, which is just a function of x.

- :

def replace(a1, ind, x):
    a2 = np.copy(a1)
    a2.put(ind,x)
    return(a2)

... .

= > -?

+4
1

, -, Scipy csr_matrix -

In [280]: a1 = np.array([1,2,3,4,5,6,7])
     ...: x = np.array([10,11,12])
     ...: ind = np.array([2,4,5])
     ...: 

In [281]: a1+csr_matrix((x-a1[ind], ([0]*x.size, ind)), (1,a1.size)).toarray()
Out[281]: array([[ 1,  2, 10,  4, 11, 12,  7]])
+2

Source: https://habr.com/ru/post/1649583/


All Articles