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
This is a pure Python implementation:
def sliding_window(arr, window=3):
i = iter(arr)
a = []
for e in range(0, window): a.append(next(i))
yield a
for e in i:
a = a[1:] + [e]
yield a
An example:
# flatten array
flatten = lambda l: [item for sublist in l for item in sublist]
a = [[0,1], [10,11], [20,21], [30,31], [40,41], [50,51]]
w = sliding_window(a, width=3)
print( list(map(flatten,w)) )
[[0, 1, 10, 11, 20, 21], [10, 11, 20, 21, 30, 31], [20, 21, 30, 31, 40, 41], [30, 31, 40, 41, 50, 51]]
Benchmark
import timeit
def benchmark():
a = [[0,1], [10,11], [20,21], [30,31], [40,41], [50,51]]
sliding_window(a, width=3)
times = timeit.Timer(benchmark).repeat(3, number=1000)
time_taken = min(times) / 1000
print(time_taken)
1.0944640007437556e-06