NumPy 2D Indexing Array

I have a little problem working with the same big data. But for now, let's assume that I have a NumPy array filled with zeros

>>> x = np.zeros((3,3)) >>> x array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]]) 

Now I want to change some of these zeros with specific values. I gave an index of the cells I want to change.

 >>> y = np.array([[0,0],[1,1],[2,2]]) >>> y array([[0, 0], [1, 1], [2, 2]]) 

And I have an array with the desired (for random) numbers, as follows

 >>> z = np.array(np.random.rand(3)) >>> z array([ 0.04988558, 0.87512891, 0.4288157 ]) 

So now I thought I could do the following:

 >>> x[y] = z 

But how does it fill the entire array like this

 >>> x array([[ 0.04988558, 0.87512891, 0.4288157 ], [ 0.04988558, 0.87512891, 0.4288157 ], [ 0.04988558, 0.87512891, 0.4288157 ]]) 

But I was hoping to get

 >>> x array([[ 0.04988558, 0, 0 ], [ 0, 0.87512891, 0 ], [ 0, 0, 0.4288157 ]]) 

EDIT

Now I used the diagonal index, but in this case my index is not just diagonal. I was hoping for the following work:

 >>> y = np.array([[0,1],[1,2],[2,0]]) >>> x[y] = z >>> x >>> x array([[ 0, 0.04988558, 0 ], [ 0, 0, 0.87512891 ], 0.4288157, 0, 0 ]]) 

But it fills the whole array as above

+4
source share
1 answer

Array indexing is slightly different on multidimensional arrays

If you have a vector, you can access the first three elements using

 x[np.array([0,1,2])] 

but when you use this on a matrix, it will return the first few rows. At first glance, using

 x[np.array([0,0],[1,1],[2,2]])] 

sounds reasonable. However, indexing a NumPy array works differently: it still processes all of these indexes in 1D mode, but returns values ​​from a vector in the same form as your index vector.

For proper access to two-dimensional matrices, you need to separate both components into two separate arrays:

 x[np.array([0,1,2]), np.array([0,1,2])] 

This will allow you to get all the elements on the main diagonal of your matrix. Appointments using this method are also possible:

 x[np.array([0,1,2]), np.array([0,1,2])] = 1 

So, in order to access the elements specified in your edit, you must do the following:

 x[np.array([0,1,2]), np.array([1,2,0])] 
+5
source

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


All Articles