w3resource

How to flatten a 3D NumPy array and print its Strides?


8. 3D Array Fortran Order Flattening

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.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to flatten a 3D array using both 'C' and 'F' orders and compare the differences in the output.
  • Write a NumPy program to create a 3D array, flatten it with ravel(order='F'), and analyze how the memory layout affects the result.
  • Write a NumPy program to check whether modifying the ravel(order='F') output affects the original 3D array.
  • Write a NumPy program to display and compare the strides of a 3D array before flattening and after flattening in Fortran order.

Go to:


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?

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.



Follow us on Facebook and Twitter for latest update.