Why does numpy indexing work differently in higher dimensions?

I have a large array and I need to change some of its values, but get inconsistent results depending on the number of measurements. A minimal example is as follows:

a=np.zeros((3,3))
indx=np.array([2,4,6])
a[np.unravel_index(indx, (3,3))] = 1

works as expected. However, the following:

b=np.zeros((1,3,3))
indx=np.array([2,4,6])
b[0,np.unravel_index(indx, (3,3))] = 1

and gives an array filled with 1.

Questions: Why is this not the same thing? And how can I match the behavior of the first example, when in fact I have a higher dimensional array, as in the second example?

+4
source share
3 answers

What produces unravel_index?

In [126]: indx=np.array([2,4,6])    
In [128]: i=np.unravel_index(indx,(3,3))    
In [129]: i
Out[129]: (array([0, 1, 2]), array([2, 1, 0]))

A tuple of 2 indexing arrays. Apply this to the 2d array, and we see that it sets the opposite diagonal.

In [130]: a=np.zeros((3,3),int)

In [131]: a[i]=1

In [132]: a
Out[132]: 
array([[0, 0, 1],
       [0, 1, 0],
       [1, 0, 0]])

2- 3D-? 3 , ?

In [133]: a=np.zeros((2,3,3),int)

In [134]: a[1,[0,1,2],[2,1,0]]=1
#  a[(1,[0,1,2],[2,1,0])]=1  is the same thing

In [135]: a
Out[135]: 
array([[[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 1],
        [0, 1, 0],
        [1, 0, 0]]])

, : (array([0, 1, 2]), array([2, 1, 0])) (1,[0,1,2],[2,1,0])?

1- (1,3,3) , 3- . (2,3,3) .

In [140]: np.unravel_index(indx,(1,3,3))
Out[140]: (array([0, 0, 0]), array([0, 1, 2]), array([2, 1, 0]))

?

In [142]: (1,)+np.unravel_index(indx,(3,3))
Out[142]: (1, array([0, 1, 2]), array([2, 1, 0]))

numpy, , , .

:

In [153]: ind=[1,0,0]
In [154]: ind[1:]=np.unravel_index(indx,(3,3))
In [155]: a[tuple(ind)]=2
+1

:

b[np.unravel_index(indx, (1,3,3))] = 1
+1

unravel_index(indx, (3,3)) 2, len((3,3))==2. 3- 1- , , length==3:

b[ ([0,0,0],) + np.unravel_index(indx, (3,3)) ] = 1
b
=> array([[[ 0.,  0.,  1.],
           [ 0.,  1.,  0.],
           [ 1.,  0.,  0.]]])

, 1, [0,0,0] , .


:

:

k = np.unravel_index(indx, (3,3))

Then you want:

b[0,k[0],k[1]] = 1

This is not the same as what you are trying:

b[0,k] = 1

By the way, a simplified version also works. The first element of the tuple should not be an array:

j = (0,) + np.unravel_index(indx, (3,3))
j
=> (0, array([0, 1, 2]), array([2, 1, 0]))
b[j] = 1
+1
source

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


All Articles