How to reshape a 2D NumPy array to a 3D array?
7. 2D to 3D Array Reshape
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:
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.
For more Practice: Solve these Related Problems:
- Write a NumPy program to reshape a 2D array into a 3D array with two different valid shapes and compare their strides.
- Write a NumPy program to reshape a 2D array into a 3D array and then back into 2D, verifying that the original order is preserved.
- Write a NumPy program to reshape a 2D array into a 3D array and check if the total number of elements remains constant.
- Write a NumPy program to attempt an invalid reshape on a 2D array and gracefully handle the resulting error.
Go to:
Previous: How to reshape a 1D NumPy array to multiple dimensions?
Next: How to flatten a 3D NumPy array and print its Strides?
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.