Skip to main content

13.5) Array Reshaping


There are a number of array methods that you can use to manipulate arrays. For example, you might want to reshape an array:

>>> a = np.arange(20).reshape(4, 5)
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

The array is reshaped following the last dimension first (i.e. columns)

Another function called resize performs the same action as reshape, but instead of returning a new array it modifies the array given:

>>> a.resize((5,4))
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])

Also try a.ravel() to flatten an array and a.transpose() to transpose an array.

Have a look at the functions for array manipulations so you know what’s available: http://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html