Reshape Array in NumPy

NumPy – Reshape Array

To reshape a given array to specific shape using NumPy library, we can use numpy.reshape() function.

Pass the given array, and required shape (as tuple) as arguments to the numpy.reshape() function.

Examples

1. Reshape numpy array from (3,4) to (2,6)

In the following program, we reshape a numpy array of shape (3, 4) to (2, 6).

Python Program

import numpy as np

# Reshape (3, 4) array to (6, 2)
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

shape = (6, 2)
output = np.reshape(arr, shape)

print(output)
Run Code Copy

Output

[[ 1  2]
 [ 3  4]
 [ 5  6]
 [ 7  8]
 [ 9 10]
 [11 12]]

2. Reshape numpy array from (3,4) to (-1,2)

If any of the dimension in the input shape is given as -1, then this dimension is adjusted based on the length in other dimensions.

For example, in the following program, we reshape a numpy array of shape (3, 4) to (-1, 2). Since we have -1 for the first dimension in the output shape, that dimension’s length is computed from (3*4)/(2) which is 6.

Python Program

import numpy as np

# Reshape (3, 4) array to (6, 2)
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

shape = (-1, 2)
output = np.reshape(arr, shape)

print(output)
Run Code Copy

Output

[[ 1  2]
 [ 3  4]
 [ 5  6]
 [ 7  8]
 [ 9 10]
 [11 12]]

Summary

In this NumPy Tutorial, we learned how to reshape a given numpy array in Python using numpy.reshape() function.

Code copied to clipboard successfully 👍