How to set one element of a multidimensional Numpy array using another Numpy array?

If we have a numpy array, for example:

Array = np.zeros((2, 10, 10)) 

and we want to set one of its elements, given by another

 indexes = np.array([0,0,0]) 

How can we do this?

 Array[indexes] = 5 

sets each element from the FIRST size of the array to 5

+5
source share
1 answer

With a as an array of data and idx as an array of indices, so that each row corresponds to one element that must be set in the data array, you can do -

 a[tuple(idx.T)] = 5 

Run Example -

 In [94]: a = np.zeros((2,2,3),dtype=int) In [95]: idx = np.array([[0,0,0],[1,1,0],[0,1,2]]) In [96]: a[tuple(idx.T)] = 5 In [97]: a Out[97]: array([[[5, 0, 0], [0, 0, 5]], [[0, 0, 0], [5, 0, 0]]]) In [98]: a[tuple(idx.T)] = [5,10,15] # or set different values In [99]: a Out[99]: array([[[ 5, 0, 0], [ 0, 0, 15]], [[ 0, 0, 0], [10, 0, 0]]]) 

Alternatively, we could calculate the linear indexes using np.ravel_multi_index and then perform the assignment using np.put , for example:

 np.put(a,np.ravel_multi_index(idx.T,a.shape),5) 

If you are dealing with three-dimensional arrays, we can truncate three-dimensional indexes and assign another method, for example:

 a[idx[:,0],idx[:,1],idx[:,2]] = 5 

If you need to install only one element, just do -

 a[tuple(idx)] = 5 

Run Example -

 In [118]: a = np.zeros((2,2,3),dtype=int) In [119]: idx = np.array([0,0,0]) In [120]: a[tuple(idx)] = 5 In [121]: a Out[121]: array([[[5, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0]]]) 
+7
source

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


All Articles