NumPy Array Reshaping

Array Reshaping

Reshaping means changing the shape of the array.

The shape of an array is the number of elements in each dimension.

Through reshaping, we can add or remove dimensions or change the number of elements in each dimension.

Reshape from 1-D to 2-D

Example

Convert the following 1-D array with 12 elements into a 2-D array.

The outer dimension will have 4 arrays, each containing 3 elements:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(4, 3)
print(newarr)

Run Instance

Reshape from 1-D to 3-D

Example

Convert the following 1-D array with 12 elements into a 3-D array.

The outer dimension will have 2 arrays, each containing 3 arrays, with 2 elements in each array:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(2, 3, 2)
print(newarr)

Run Instance

Can we reshape into any shape?

Yes, as long as the number of elements required for reshaping is equal in both shapes.

We can reshape the 8-element 1D array into a 2D array with 2 rows and 4 elements, but we cannot reshape it into a 3x3 2D array because that would require 3x3 = 9 elements.

Example

Attempt to convert a 1D array with 8 elements into a 2D array with 3 elements in each dimension (this will cause an error):

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
newarr = arr.reshape(3, 3)
print(newarr)

Run Instance

Return a copy or a view?

Example

Check if the returned array is a copy or a view:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
print(arr.reshape(2, 4).base)

Run Instance

The example above returns the original array, so it is a view.

Unknown Dimension

You can use an 'unknown' dimension.

This means you do not have to specify an exact number for one of the dimensions in the reshape method.

Pass -1 As a value, NumPy will calculate this number for you.

Example

Convert an 8-element 1D array to a 2x2 element 3D array:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
newarr = arr.reshape(2, 2, -1)
print(newarr)

Run Instance

Note:We cannot convert -1 pass to more than one dimension.

Flatten Arrays

Flattening the arrays means converting multi-dimensional arrays to 1D arrays.

We can use reshape(-1) to do this.

Example

Convert the array to a 1D array:

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
newarr = arr.reshape(-1)
print(newarr)

Run Instance

Note:There are many functions that can change the shape of numpy flatten, ravel, and can also rearrange elements rot90, flip, fliplr, flipud, etc. These functions belong to the intermediate to advanced part of numpy.