How to create and reshape a 3D NumPy array using ravel()?
NumPy: Memory Layout Exercise-4 with Solution
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:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: How to create and flatten a 2D NumPy array using ravel()?
Next: How to create and change Strides of a 2D NumPy array?
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/create-and-reshape-a-3d-numpy-array-using-ravel.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics