How does numpy.swapaxes work?

前端 未结 2 1821
终归单人心
终归单人心 2020-12-16 01:32

I created a sample array:

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

On printing, I get this as output:

[[ 0  1]
[ 2  3]
[ 4  5]
[ 6  7         


        
2条回答
  •  有刺的猬
    2020-12-16 02:08

    Start with the reshape

    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]]])
    

    This displays as 2 planes, and each plane is a 3x3. Is that part clear? The fact that the array was shaped (9,2) at one point isn't significant. Reshaping doesn't change the order of elements.

    Apply the swapaxes. Shape is now (3,3,2). 3 planes, each is 3x2. This particular swap is the same as a transpose

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

    The middle axis is unchanged. There are still columns of [0,3,6], [9,12,15], etc.

    It may be easier to visualize the change with 3 different sized axes

    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]]])
    

    Notice what happens when I flatten the array

    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])
    

    the order of terms has been shuffled. As created it was [0,1,2,3...]. Now the 1 is the 6th term (2x3).

    Under the covers numpy actually performs the swap or transpose by changing shape, strides and order, without changing the data buffer (i.e. it's a view). But further reshaping, including raveling, forces it to make a copy. But that might be more confusing than helpful at this stage.

    In numpy axes are numbered. Terms like x,y,z or planes, rows, columns may help you map those on to constructs that you can visualize, but they aren't 'built-in'. Describing the swap or transpose in words is tricky.

提交回复
热议问题