w3resource

Creating and reshaping a 2D NumPy array


18. 2D to 3D Reshape Variation

Write a NumPy program that creates a 2D array of shape (4, 6), then reshape it into a 3D array of shape (2, 2, 6). Print the original and reshaped arrays.

Sample Solution:

Python Code:

import numpy as np

# Step 1: Create a 2D array of shape (4, 6)
original_2d_array = np.random.rand(4, 6)
print("Original 2D array:\n", original_2d_array)

# Step 2: Reshape the 2D array into a 3D array of shape (2, 2, 6)
reshaped_3d_array = original_2d_array.reshape(2, 2, 6)
print("\nReshaped 3D array:\n", reshaped_3d_array)

Output:

Original 2D array:
 [[0.62709246 0.23292313 0.94462683 0.96736515 0.61750314 0.11905439]
 [0.35378285 0.03013207 0.95206969 0.38529313 0.83720405 0.55076462]
 [0.04496562 0.16134742 0.49377059 0.23158711 0.92115743 0.55099414]
 [0.50158092 0.39983701 0.57911658 0.48010662 0.55052127 0.29038728]]

Reshaped 3D array:
 [[[0.62709246 0.23292313 0.94462683 0.96736515 0.61750314 0.11905439]
  [0.35378285 0.03013207 0.95206969 0.38529313 0.83720405 0.55076462]]

 [[0.04496562 0.16134742 0.49377059 0.23158711 0.92115743 0.55099414]
  [0.50158092 0.39983701 0.57911658 0.48010662 0.55052127 0.29038728]]]

Explanation:

  • Create a 2D array: A 2D array of shape (4, 6) is created using np.random.rand().
  • Reshape to 3D: The 2D array is reshaped into a 3D array with shape (2, 2, 6).

For more Practice: Solve these Related Problems:

  • Write a NumPy program to reshape a 2D array into two different 3D shapes and compare the element ordering in each case.
  • Write a NumPy program to verify that reshaping a 2D array into 3D preserves element order by flattening both arrays.
  • Write a NumPy program to reshape a 2D array into a 3D array and then apply an axis permutation to analyze the impact on strides.
  • Write a NumPy program to create a 2D array, reshape it into a 3D array, and then apply a mathematical function to verify data consistency.

Go to:


Previous: Creating and reshaping a 4D NumPy array
Next: Creating and slicing a 1D NumPy array.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.