How to flatten a 3D NumPy array and print its Strides?
NumPy: Memory Layout Exercise-8 with Solution
Write a NumPy program that creates a 3D array of shape (2, 4, 4) and print the strides. Then, flatten it with ravel(order='F') and print the flattened array.
Sample Solution:
Python Code:
import numpy as np
# Create a 3D array of shape (2, 4, 4)
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, 28],
[29, 30, 31, 32]]])
# Print the strides of the 3D array
print("Strides of the 3D array:", array_3d.strides)
# Flatten the array with ravel(order='F')
flattened_array = array_3d.ravel(order='F')
# Print the flattened array
print("Flattened array (column-major order):", flattened_array)
Output:
Strides of the 3D array: (64, 16, 4) Flattened array (column-major order): [ 1 17 5 21 9 25 13 29 2 18 6 22 10 26 14 30 3 19 7 23 11 27 15 31 4 20 8 24 12 28 16 32]
Explanation:
- Import NumPy library: We start by importing the NumPy library to work with arrays.
- Create a 3D array: We create a 3D array array_3d of shape (2, 4, 4) using np.array().
- Print the strides: We print the strides of array_3d using the strides attribute. Strides indicate the number of bytes to step in each dimension when traversing an array.
- Flatten with ravel(order='F'): We use the ravel() method with order='F' (column-major order) to flatten the 3D array into a 1D array, stored in flattened_array.
- Print the flattened array: Finally, we print the flattened array flattened_array.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: How to reshape a 2D NumPy array to a 3D array?
Next: How to reshape and modify a 1D NumPy array to a 3x3 matrix?
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://198.211.115.131/python-exercises/numpy/flatten-a-3d-numpy-array-and-print-its-strides.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics