Manipulating array shapes

Besides reshape() another repeating chore is flattering. Flattering means transforming a multidimensional array into a one-dimensional array. We can manipulate array shapes in several ways:

Using ravel() function

import numpy as np

b = np.arange(36).reshape(3,3,4)
b

#out
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]],

       [[24, 25, 26, 27],
        [28, 29, 30, 31],
        [32, 33, 34, 35]]])
b.ravel()

#out
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, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
       34, 35])

The ravel() just gives back a view of the array without allocating new memory.

Using flatten() function

b.ravel()

#out
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, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
       34, 35])

The flatten() returns the same result as ravel() but it allocates new memory.

Using a tuple

We can define the shape using a tuple. The code shown below creates a 9×4 array.

b.shape = (9, 4)
b

#out
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],
       [24, 25, 26, 27],
       [28, 29, 30, 31],
       [32, 33, 34, 35]])

Using transpose() function

The transpose() means that rows become columns and columns become rows.

b.transpose()

#out
array([[[ 0, 12, 24],
        [ 4, 16, 28],
        [ 8, 20, 32]],

       [[ 1, 13, 25],
        [ 5, 17, 29],
        [ 9, 21, 33]],

       [[ 2, 14, 26],
        [ 6, 18, 30],
        [10, 22, 34]],

       [[ 3, 15, 27],
        [ 7, 19, 31],
        [11, 23, 35]]])

Using resize() function

The resize() works just like reshape().

b.resize((2,18))
b

#out
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, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
        35]])

Leave a Reply