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

后端 未结 6 746
日久生厌
日久生厌 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:16

    Here is One-liner using Numpy >= v1.17

    rowsJoined = 3
    
    splits = np.vstack(np.split(x,np.array([[i, i + rowsJoined] for i in range(x.shape[0] - (rowsJoined - 1))]).reshape(-1))).reshape(-1, rowsJoined * x.shape[1]) 
    

    Test

    x = np.array([[00,1],
                  [10,11],
                  [20,21],
                  [30,31],
                  [40,41],
                  [50,51]])
    

    Result

    [[ 0  1 10 11 20 21]
     [10 11 20 21 30 31]
     [20 21 30 31 40 41]
     [30 31 40 41 50 51]]
    

    Test Performance On Large Array

    import numpy as np
    import time
    
    x = np.array(range(1000)).reshape(-1, 2)
    rowsJoined = 3
    
    all_t = 0.
    for i in range(1000):
        start_ = time.time()
        np.vstack(
            numpy.split(x,np.array([[i, i + rowsJoined] for i in range(x.shape[0] - (rowsJoined - 1))])
                        .reshape(-1))).reshape(-1, rowsJoined * x.shape[1])
        all_t += time.time() - start_
    
    print('Average Time of 1000 Iterations on Array of Shape '
          '1000 x 2 is: {} Seconds.'.format(all_t/1000.))
    

    Performance Result

    Average Time of 1000 Iterations on Array of Shape 1000 x 2 is: 0.0016909 Seconds.
    

提交回复
热议问题