0

I would like to slide a ND numpy array. Currently, the code below do the work.

import numpy as np
arr = np.array([np.arange(0,16), np.arange(17,33),np.arange(33,49)])
window_size=4
expected_opt=[arr [:, i:i+window_size]for i in range(0,16,window_size)]

But I curious whether there is more efficient way to achieve similar objective.

one might suggest 1, but the solution gives different output.

mpx
  • 3,081
  • 2
  • 26
  • 56

1 Answers1

1

You are looking at a reshape, not rolling:

arr.reshape(arr.shape[0],-1,window_size).transpose(1,0,2)

Output:

array([[[ 0,  1,  2,  3],
        [17, 18, 19, 20],
        [33, 34, 35, 36]],

       [[ 4,  5,  6,  7],
        [21, 22, 23, 24],
        [37, 38, 39, 40]],

       [[ 8,  9, 10, 11],
        [25, 26, 27, 28],
        [41, 42, 43, 44]],

       [[12, 13, 14, 15],
        [29, 30, 31, 32],
        [45, 46, 47, 48]]])
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74