w3resource

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

NumPy: Memory Layout Exercise-5 with Solution

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:

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

Previous: How to create and reshape a 3D NumPy array using ravel()?
Next: How to reshape a 1D NumPy array to multiple dimensions?

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://198.211.115.131/python-exercises/numpy/create-and-change-strides-of-a-2d-numpy-array.php