Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set single element of multi dimensional Numpy Array using another Numpy array?

If we have a numpy array like:

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

and we want to set one element of it, given by another

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

How can we do that?

Array[indexes] = 5 

is setting every element of the FIRST dimension of Array to 5

like image 440
Fosa Avatar asked Jan 23 '17 08:01

Fosa


People also ask

How do I append a NumPy array to another NumPy array?

You can append a NumPy array to another NumPy array by using the append() method. In this example, a NumPy array “a” is created and then another array called “b” is created. Then we used the append() method and passed the two arrays.

How do I connect two NumPy arrays?

Use numpy. concatenate() to merge the content of two or multiple arrays into a single array. This function takes several arguments along with the NumPy arrays to concatenate and returns a Numpy array ndarray. Note that this method also takes axis as another argument, when not specified it defaults to 0.

How do you make a NumPy array 1-dimensional to 2 dimensional?

convert a 1-dimensional array into a 2-dimensional array by adding new axis. a=np. array([10,20,30,40,50,60]) b=a[:,np. newaxis]--it will convert it to two dimension.


1 Answers

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

a[tuple(idx.T)] = 5

Sample run -

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 compute the linear indices with np.ravel_multi_index and then perform the assignment with np.put, like so -

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

If you are dealing with three dimensional arrays, we could slice the three dimensional indices and assign to have another method, like so -

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

If it's just one element needed to be set, just do -

a[tuple(idx)] = 5

Sample run -

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]]])
like image 81
Divakar Avatar answered Sep 20 '22 03:09

Divakar