0

Let's say I have a np.array such as:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Given a window of size 5, I want to and get:

0, 1, 2, 3, 4
1, 2, 3, 4, 5
2, 3, 4, 5, 6
3, 4, 5, 6, 7
4, 5, 6, 7, 8
5, 6, 7, 8, 9
6, 7, 8, 9, 10

It's an easy problem any rookie can solve, just wanted to know what is the most Pythonic numpy implementation.

Leevo
  • 1,683
  • 2
  • 17
  • 34

1 Answers1

0

Depends on how badly you want to avoid copying that data. If badly enough, use np.lib.stride_tricks.as_strided:

arr = np.arange(11)
window = 7
as_strided(arr, shape=(window, arr.size - window + 1), strides=arr.strides * 2, writeable=False)

This will make an array that has views of the same element in multiple places, so I've set writable=False. You can always make an expanded copy if you like.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264