w3resource

How to transpose a 2D NumPy array and print strides?

NumPy: Memory Layout Exercise-15 with Solution

Write a NumPy program that creates a 2D array of shape (3, 3), make a transposed view using .T, and print the strides of both the original and transposed arrays.

Sample Solution:

Python Code:

import numpy as np

# Create a 2D array of shape (3, 3)
array_2d = np.array([[1, 2, 3],
                     [4, 5, 6],
                     [7, 8, 9]])

# Make a transposed view of the array using .T
transposed_array = array_2d.T

# Print the strides of the original array
print("Strides of the original array:", array_2d.strides)

# Print the strides of the transposed array
print("Strides of the transposed array:", transposed_array.strides)

Output:

Strides of the original array: (12, 4)
Strides of the transposed array: (4, 12)

Explanation:

  • Import NumPy library: We start by importing the NumPy library to handle array operations.
  • Create a 2D array: We create a 2D array array_2d of shape (3, 3) using np.array().
  • Transpose the array: We create a transposed view of array_2d using the .T attribute, resulting in transposed_array.
  • Print strides of original array: We print the strides of array_2d using the strides attribute to understand the memory layout.
  • Print strides of transposed array: We print the strides of transposed_array to see how the memory layout changes after transposition.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: How to flatten a 2D NumPy array in 'C' and 'F' order?
Next: How to slice a Sub-array from a reshaped 1D NumPy array and print strides?

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://w3resource.com/python-exercises/numpy/transpose-a-2d-numpy-array-and-print-strides.php