In python, reshaping numpy array can be very critical while creating a matrix or tensor from vectors. In order to reshape numpy array of one dimension to n dimensions one can use np.reshape()
method. Let’s check out some simple examples.
It is very important to reshape you numpy array, especially you are training with some deep learning network. Deep Learning models like CNN or LSTM in keras or any other python deep learning library some time requires reshaping of original numpy array.
Checking Shape of Existing numpy array
You can check shape of an existing array using shape attribute of numpy array.
1 2 3 4 5 6 7 8 9 | # Prerequisite: Import numpy import numpy as np # Get a 2d matrix and print shape arr = np.array([[11, 12, 13, 14, 15], [21, 22, 23, 24, 25]]) arr.shape #>> (2, 5) |
If we check the shape of reshaped numpy array, we’ll find tuple (2, 5) which is a new shape of numpy array. Here first element of tuple is number of rows and second is number of columns.

Reshaping numpy array (vector to matrix)
1 2 3 4 5 6 7 8 9 10 11 12 13 | # Create a numpy array arr = np.arange(9) # Reshaping to 3x3 Matrix arr = arr.reshape(3, 3) arr #>> array([[0, 1, 2], #>> [3, 4, 5], #>> [6, 7, 8]]) # Check new shape arr.shape #>> (3, 3) |
Reshaping numpy array (matrix to tensor)
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 | # Matrix arr = np.array([[11, 12, 13, 14], [21, 22, 23 ,24], [31, 32, 33 ,34], [41, 42, 43 ,44]]) # Reshaped to Tensor arr = arr.reshape(4,4,1) arr #>> array([[[11], #>> [12], #>> [13], #>> [14]], #>> #>> [[21], #>> [22], #>> [23], #>> [24]], #>> #>> [[31], #>> [32], #>> [33], #>> [34]], #>> #>> [[41], #>> [42], #>> [43], #>> [44]]]) |
How reshaping works with numpy arrays?

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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | # Reshaping Illustration arr = np.array([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]) # Check original shape print(arr.shape) #>> (3, 4) # Reshape to (4,3) arr = arr.reshape(4,3) arr #>> array([[1, 1, 1], #>> [1, 2, 2], #>> [2, 2, 3], #>> [3, 3, 3]]) # Reshape to (6,2) arr = arr.reshape(6,2) arr #>> array([[1, 1], #>> [1, 1], #>> [2, 2], #>> [2, 2], #>> [3, 3], #>> [3, 3]]) # Reshape to (2, 6) arr = arr.reshape(2, 6) arr #>> array([[1, 1, 1, 1, 2, 2], #>> [2, 2, 3, 3, 3, 3]]) # Reshape to (1, 12) arr = arr.reshape(1, 12) arr #>> array([[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]]) # Reshape to (12, 1) arr = arr.reshape(12, 1) arr #>> array([[1], #>> [1], #>> [1], #>> [1], #>> [2], #>> [2], #>> [2], #>> [2], #>> [3], #>> [3], #>> [3], #>> [3]]) |
Hope you like this short and sweet information on reshaping numpy array example. Stay tuned for more examples.
Leave a Reply