Assuming I have a numpy array such as
[0, 1, 2, 3, 4, 5]
How do I create a 2D matrix from each 3 elements, like so:
[
[0,1,2],
[1,2,3],
[2,3,4],
[3,4,5]
]
Is there a more efficient way than using a for loop?
Thanks.
>Solution :
Yes, you can use a sliding window view:
import numpy as np
arr = np.arange(6)
view = np.lib.stride_tricks.sliding_window_view(arr, 3)
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[3, 4, 5]])
Keep in mind however that this is a view of the original array, not a new array.