Numpy 3D array transposed when indexing in one step compared to two steps

import numpy as np
x = np.random.randn(2, 3, 4)
mask = np.array([1, 0, 1, 0], dtype=np.bool)
y = x[0, :, mask]
z = x[0, :, :][:, mask]
print(y)
print(z)
print(y.T)

Why does the above operation in two stages lead to the transposition of its implementation in one step?

+4
source share
1 answer

Here's the same behavior with a list index:

In [87]: x=np.arange(2*3*4).reshape(2,3,4)
In [88]: x[0,:,[0,2]]
Out[88]: 
array([[ 0,  4,  8],
       [ 2,  6, 10]])
In [89]: x[0,:,:][:,[0,2]]
Out[89]: 
array([[ 0,  2],
       [ 4,  6],
       [ 8, 10]])

In the second case, it x[0,:,:]returns an array (3,4), and the next index selects 2 columns.

In the first case, he first selects the first and last measurements and adds a slice (average size). 0and [0,2]make a measurement 2, and is added 3from the middle, giving the form (2,3).

This is a case of mixed basic and advanced indexing.

http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing

, , , - .

, . , . x[:,ind_1,:,ind_2], ind_1 ind_2 3d ( ).

:

numpy?

numpy

===========================

- -

In [221]: x[0,np.array([0,1,2])[:,None],[0,2]]
Out[221]: 
array([[ 0,  2],
       [ 4,  6],
       [ 8, 10]])
In [222]: np.ix_([0],[0,1,2],[0,2])
Out[222]: 
(array([[[0]]]), array([[[0],
         [1],
         [2]]]), array([[[0, 2]]]))
In [223]: x[np.ix_([0],[0,1,2],[0,2])]
Out[223]: 
array([[[ 0,  2],
        [ 4,  6],
        [ 8, 10]]])

3d, (1,3,2). ix_ 0. ix_:

In [224]: i,j=np.ix_([0,1,2],[0,2])
In [225]: x[0,i,j]
Out[225]: 
array([[ 0,  2],
       [ 4,  6],
       [ 8, 10]])

, (2,1,3):

In [232]: i,j=np.ix_([0,2],[0])
In [233]: x[j,:,i]
Out[233]: 
array([[[ 0,  4,  8]],

       [[ 2,  6, 10]]])
+5

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


All Articles