w3resource

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


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: