How to reshape a 2D NumPy array to a 3D array?
NumPy: Memory Layout Exercise-7 with Solution
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:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: How to reshape a 1D NumPy array to multiple dimensions?
Next: How to flatten a 3D NumPy array and print its Strides?
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://www.w3resource.com/python-exercises/numpy/reshape-a-2d-numpy-array-to-a-3d-array.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics