Sliding windows from 2D array that slides along axis=0 or rows to give a 3D array

前端 未结 1 1532
灰色年华
灰色年华 2020-12-18 08:49

I have a 2-d numpy array of this form:

[[  0.   1.   2.   3.   4.]
 [  5.   6.   7.   8.   9.]
 [ 10.  11.  12.  13.  14.]
 [ 15.  16.  17.  18.  19.]
 [ 20.         


        
相关标签:
1条回答
  • 2020-12-18 09:25

    Here's an approach with requested np.lib.stride_tricks.as_strided -

    def strided_axis0(a, L): 
        # INPUTS :
        # a is array
        # L is length of array along axis=0 to be cut for forming each subarray
    
        # Length of 3D output array along its axis=0
        nd0 = a.shape[0] - L + 1
    
        # Store shape and strides info
        m,n = a.shape
        s0,s1 = a.strides
    
        # Finally use strides to get the 3D array view
        return np.lib.stride_tricks.as_strided(a, shape=(nd0,L,n), strides=(s0,s0,s1))
    

    Sample run -

    In [48]: X = np.arange(35).reshape(-1,5)
    
    In [49]: X
    Out[49]: 
    array([[ 0,  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, 26, 27, 28, 29],
           [30, 31, 32, 33, 34]])
    
    In [50]: strided_axis0(X, L=4)
    Out[50]: 
    array([[[ 0,  1,  2,  3,  4],
            [ 5,  6,  7,  8,  9],
            [10, 11, 12, 13, 14],
            [15, 16, 17, 18, 19]],
    
           [[ 5,  6,  7,  8,  9],
            [10, 11, 12, 13, 14],
            [15, 16, 17, 18, 19],
            [20, 21, 22, 23, 24]],
    
           [[10, 11, 12, 13, 14],
            [15, 16, 17, 18, 19],
            [20, 21, 22, 23, 24],
            [25, 26, 27, 28, 29]],
    
           [[15, 16, 17, 18, 19],
            [20, 21, 22, 23, 24],
            [25, 26, 27, 28, 29],
            [30, 31, 32, 33, 34]]])
    
    0 讨论(0)
提交回复
热议问题