How does numpy.swapaxes work?

I created an array of samples:

a = np.arange(18).reshape(9,2)

When printing, I get this as output:

[[ 0  1]
[ 2  3]
[ 4  5]
[ 6  7]
[ 8  9]
[10 11]
[12 13]
[14 15]
[16 17]]

When performing this rebuild:

b = a.reshape(2,3,3).swapaxes(0,2)

I get:

[[[ 0  9]
[ 3 12]
[ 6 15]]

[[ 1 10]
[ 4 13]
[ 7 16]]

[[ 2 11]
[ 5 14]
[ 8 17]]]

I went through this question, but it does not solve my problem.

Change array in numpy

Documentation is also not useful.

https://docs.scipy.org/doc/numpy/reference/generated/numpy.swapaxes.html

I need to know how swap works (x axis, y axis, z axis). The most useful would be a schematic explanation.

+4
source share
2 answers

Start by changing the shape.

In [322]: a = np.arange(18).reshape(2,3,3)
In [323]: a
Out[323]: 
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]]])

2 , 3x3. ? , (9,2) - , . .

swapaxes. (3,3,2). 3 , 32. ,

np.arange(18).reshape(2,3,3).transpose(2,1,0)

. [0,3,6], [9,12,15] ..

.

In [335]: a=np.arange(2*3*4).reshape(2,3,4)
In [336]: a
Out[336]: 
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
In [337]: a.swapaxes(0,2)
Out[337]: 
array([[[ 0, 12],
        [ 4, 16],
        [ 8, 20]],

       [[ 1, 13],
        [ 5, 17],
        [ 9, 21]],

       [[ 2, 14],
        [ 6, 18],
        [10, 22]],

       [[ 3, 15],
        [ 7, 19],
        [11, 23]]])

, ,

In [338]: a.swapaxes(0,2).ravel()
Out[338]: 
array([ 0, 12,  4, 16,  8, 20,  1, 13,  5, 17,  9, 21,  2, 14,  6, 18, 10,
       22,  3, 15,  7, 19, 11, 23])

. [0,1,2,3...]. 1 - (2x3).

numpy , shape, strides order, (.. ). , , . , .

numpy . , x, y, z , , , , , "". swap .

+6

swapaxes

,

In [1]: arr = np.arange(16).reshape((2, 2, 4))

In [2]: arr
Out[2]: 
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [12, 13, 14, 15]]])

arr (2, 2, 4), 7

In [3]: arr[0, 1, 3]
Out[3]: 7

3 0, 1 2, 0 2

In [4]: arr_swap = arr.swapaxes(0, 2)

In [5]: arr_swap
Out[5]: 
array([[[ 0,  8],
        [ 4, 12]],

       [[ 1,  9],
        [ 5, 13]],

       [[ 2, 10],
        [ 6, 14]],

       [[ 3, 11],
        [ 7, 15]]])

, 7 (3, 1, 0), 1 ,

In [6]: arr_swap[3, 1, 0]
Out[6]: 7

, , , .

In [7]: arr[0, 0, 1]
Out[7]: 1

In [8]: arr_swap[1, 0, 0]
Out[8]: 1

In [9]: arr[0, 1, 2]
Out[9]: 6

In [9]: arr_swap[2, 1, 0]
Out[9]: 6

, , , arr_swap[2, 1, 0] = arr[0, 1, 2].

0

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


All Articles