w3resource

How to create and change Strides of a 2D NumPy array?


Write a NumPy program to create a 2D array of shape (5, 5) and change its strides to view every other element in the first dimension.

Sample Solution:

Python Code:

import numpy as np

# Create a 2D array of shape (5, 5)
array_2d = 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]])

# Change the strides to view every other element in the first dimension
strided_array = array_2d[::2, :]

# Print the strided array
print(strided_array)

Output:

[[ 1  2  3  4  5]
 [11 12 13 14 15]
 [21 22 23 24 25]]

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 (5, 5) using np.array().
  • Change the strides: We use slicing with strides ::2 to view every other element in the first dimension, resulting in strided_array.
  • Print the result: Finally, we print the strided_array.

Python-Numpy Code Editor: