How to take subarrays from NumPy array with given stride/stepsize?

Given a NumPy array, we have to take subarrays from it with given stride/stepsize. By Pranit Sharma Last updated : December 27, 2023

A subarray is part of an array that contains a random set of elements in the original sequence. For example, for an array [1,2,3,4,5], the sub-arrays can be [1,2,3], [2,3,4], etc. Note that [1,3,5] can not be a subarray for this array.

Problem statement

Suppose that we are given a numpy array and we need to create a matrix of sub-sequences from this array of length 5 with stride 3.

Here, length refers to the number of elements in a subarray and stride refers to the number of subarrays we need to create.

NumPy Array - Taking subarrays with given stride/stepsize

To take subarrays from NumPy array with given stride/stepsize, we can use the broadcasting technique by adding a new axis using the None in indexing. Also, we can define the number of rows using the size of the original array, the length of the subarrays, and the strides.

Let us understand with the help of an example,

Python code to take subarrays from NumPy array with given stride/stepsize

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

# Display original array
print("original array:\n",arr,"\n")

# Defining a function
def fun(a, L, S):
    rows = ((a.size-L)//S)+1
    n = a.strides[0]
    return np.lib.stride_tricks.as_strided(a, shape=(rows,L), strides=(S*n,n))

# Getting a subarray matrix
res = fun(arr,5,3)

# Display result
print("Result:\n",res)

Output

Example: How to take subarrays from NumPy array with given stride/stepsize?

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.