w3resource

Creating and reshaping a 2D NumPy array

NumPy: Memory Layout Exercise-18 with Solution

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).

Python-Numpy Code Editor:

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

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/creating-and-reshaping-a-2d-numpy-array.php