sliding window of M-by-N shape numpy.ndarray

后端 未结 6 768
日久生厌
日久生厌 2020-11-28 22:20

I have a numpy array of shape (6,2)

[[00,01],
 [10,11],
 [20,21],
 [30,31],
 [40,41],
 [50,51]]

I need a sliding window with step size 1 an

6条回答
  •  难免孤独
    2020-11-28 23:14

    You can do a vectorized sliding window in numpy using fancy indexing.

    >>> import numpy as np
    
    >>> a = np.array([[00,01], [10,11], [20,21], [30,31], [40,41], [50,51]])
    
    >>> a
    array([[ 0,  1],
           [10, 11],
           [20, 21],                      #define our 2d numpy array
           [30, 31],
           [40, 41],
           [50, 51]])
    
    >>> a = a.flatten()
    
    >>> a
    array([ 0,  1, 10, 11, 20, 21, 30, 31, 40, 41, 50, 51])    #flattened numpy array
    
    >>> indexer = np.arange(6)[None, :] + 2*np.arange(4)[:, None]
    
    >>> indexer
    array([[ 0,  1,  2,  3,  4,  5],
           [ 2,  3,  4,  5,  6,  7],            #sliding window indices
           [ 4,  5,  6,  7,  8,  9],
           [ 6,  7,  8,  9, 10, 11]])
    
    >>> a[indexer]
    array([[ 0,  1, 10, 11, 20, 21],
           [10, 11, 20, 21, 30, 31],            #values of a over sliding window
           [20, 21, 30, 31, 40, 41],
           [30, 31, 40, 41, 50, 51]])
    
    >>> np.sum(a[indexer], axis=1)
    array([ 63, 123, 183, 243])         #sum of values in 'a' under the sliding window.
    

    Explanation for what this code is doing.

    The np.arange(6)[None, :] creates a row vector 0 through 6, and np.arange(4)[:, None] creates a column vector 0 through 4. This results in a 4x6 matrix where each row (six of them) represents a window, and the number of rows (four of them) represents the number of windows. The multiple of 2 makes the sliding window slide 2 units at a time which is necessary for sliding over each tuple. Using numpy array slicing you can pass the sliding window into the flattened numpy array and do aggregates on them like sum.

提交回复
热议问题