w3resource

How to reshape a 2D NumPy array to a 3D array?


Write a NumPy program that creates a 2D array of shape (6, 2) and use reshape() to change it into a 3D array of shape (2, 3, 2). Print the new array.

Sample Solution:

Python Code:

import numpy as np

# Create a 2D array of shape (6, 2)
array_2d = np.array([[1, 2],
                     [3, 4],
                     [5, 6],
                     [7, 8],
                     [9, 10],
                     [11, 12]])

# Use reshape() to change the shape to (2, 3, 2)
array_3d = array_2d.reshape(2, 3, 2)

# Print the new 3D array
print(array_3d)

Output:

[[[ 1  2]
  [ 3  4]
  [ 5  6]]

 [[ 7  8]
  [ 9 10]
  [11 12]]]

Explanation:

  • Import NumPy library: We start by importing the NumPy library to work with arrays.
  • Create a 2D array: We create a 2D array array_2d of shape (6, 2) using np.array().
  • Reshape to (2, 3, 2): We use the reshape() method to change the shape of array_2d to (2, 3, 2), resulting in array_3d.
  • Print the result: Finally, we print the new 3D array array_3d.

Python-Numpy Code Editor: