Getting subarrays from a numpy array with a given step / step

Let's say I have an array of Python Numpy a arrays.

numpy.array([1,2,3,4,5,6,7,8,9,10,11].) 

I want to create a subsequence matrix from this array of length 5 with step 3. Therefore, the result matrix will look like this:

 numpy.array([[1,2,3,4,5],[4,5,6,7,8],[7,8,9,10,11]]) 

One possible way to implement this would be to use a for loop.

 result_matrix = np.zeros((3, 5)) for i in range(0, len(a), 3): result_matrix[i] = a[i:i+5] 

Is there a cleaner way to implement this Numpy?

+9
source share
1 answer

Approach # 1: Using broadcasting -

 def broadcasting_app(a, L, S ): # Window len = L, Stride len/stepsize = S nrows = ((a.size-L)//S)+1 return a[S*np.arange(nrows)[:,None] + np.arange(L)] 

Approach # 2: Using More Effective NumPy strides -

 def strided_app(a, L, S ): # Window len = L, Stride len/stepsize = S nrows = ((a.size-L)//S)+1 n = a.strides[0] return np.lib.stride_tricks.as_strided(a, shape=(nrows,L), strides=(S*n,n)) 

Run Example -

 In [143]: a Out[143]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) In [144]: broadcasting_app(a, L = 5, S = 3) Out[144]: array([[ 1, 2, 3, 4, 5], [ 4, 5, 6, 7, 8], [ 7, 8, 9, 10, 11]]) In [145]: strided_app(a, L = 5, S = 3) Out[145]: array([[ 1, 2, 3, 4, 5], [ 4, 5, 6, 7, 8], [ 7, 8, 9, 10, 11]]) 
+16
source

Source: https://habr.com/ru/post/1274890/


All Articles