2

Let's say I have a 1D array of values:

T = np.array([1.3, 8.9, 1.4, 3.2, 4.4, 7.0, 2.0, 6.9]

and I have a list of start indices:

I = np.array([5, 2, 4, 1])

For each start index, I would like to grab m consecutive values from T starting at the start index. So, the final output for m=3 should be a 2D array with:

T = np.array([[7.0, 2.0, 6.9],
              [1.4, 3.2, 4.4],
              [4.4, 7.0, 2.0],
              [8.9, 1.4, 3.2]])

I could simply loop through the indices but I was hoping that there were a more efficient approach:

m = 3
out = np.empty((len(I), m))
for j, i in enumerate(I):
    out[j] = T[j : j+m]
slaw
  • 6,591
  • 16
  • 56
  • 109

1 Answers1

0

Here's an answer that does not require installing additional dependencies:

def rolling_window(a, window):
    a = np.asarray(a)
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)

    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

m = 3
rolling_T = rolling_window(T, m)  # Note that this is a very efficient view
out = rolling_T[I]
slaw
  • 6,591
  • 16
  • 56
  • 109