How to create strides of length n from a given 1D array?
Strides It is nothing but the tuple of integer values, in which the bytes of particular dimension is indicated by each one of in it. To tell how many bytes to jump in the data buffer Numpy uses strides. Stride will indicate the number of bytes to jump in the order for reaching to the next value in the given dimension which also known as axis of travel. It is always constant for given axis.
import numpy as np from numpy.lib.stride_tricks import as_strided
Sample_data = np.array([12,13,14,15,16,17,18,19], dtype = "int32") print("This is a Sample 1D array:", Sample_data)
This is a Sample 1D array: [12 13 14 15 16 17 18 19]
Result = np.lib.stride_tricks.as_strided(Sample_data,((8-2)//3+1,2),(3*4,4)) print("This is the Following Result","\n",Result, "\n") print("This is the shape of original array which is an 1D array:","\n",Sample_data.shape,"\n") print("This is the shape of our Result which is an 2D array:","\n",Result.shape)
This is the Following Result [[12 13] [15 16] [18 19]] This is the shape of original array which is an 1D array: (8,) This is the shape of our Result which is an 2D array: (3, 2)
In the above we have used "np.lib.stride_tricks.as_strided(array, new_array_shape, Stride_steps)" syntax for Stride in which there various functions ar working lets understand them: array - This is nothing but the original array that we want to stride. In our case we have taken 1D array of name "Sample_data". new array shape - This is nothing but the shape of our output array, in our case the resulted array is 2D so the shape will be (3,2) which means 3 rows and 2 columns. Stride steps - It is nothing but the stride that which is measured in bytes. In our case it is (12,4) because we want to jump over 3 indices in the array in which each of them is an integer i.e 4 bytes, So therefore 3*4 = 12 for row stride step and for column is 4 because the next integer is 4 bytes away.