w3resource

How to create and reshape a 3D NumPy array using ravel()?


Write a NumPy program to create a 3D array of shape (3, 3, 3), then reshape it into a 1D array using ravel() and finally print the result.

Sample Solution:

Python Code:

import numpy as np
# Create a 3D array of shape (3, 3, 3)
array_3d = np.array([[[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]]])

# Use ravel() to reshape the 3D array into a 1D array
flattened_array = array_3d.ravel()

# Print the reshaped 1D array
print(flattened_array)

Output:

[ 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]

Explanation:

  • Import NumPy library: We start by importing the NumPy library to work with arrays and matrices.
  • Create a 3D array: We create a 3D array array_3d of shape (3, 3, 3) using np.array().
  • Reshape the array: We use the ravel() method to reshape array_3d into a 1D array, stored in flattened_array.
  • Print the result: Finally, we print the reshaped 1D array.

Python-Numpy Code Editor: