1

From the following array of shape (6, 3):

>>> arr
[
    [1, 0, 1],
    [0, 0, 2],
    [1, 2, 0],
    [0, 1, 3],
    [2, 2, 1],
    [2, 0, 2]
]

I'd like to repeat the values according to a sliding window of n=4, giving a new array of shape (6-n-1, n, 3):

>>> new_arr
[
    [
        [1, 0, 1],
        [0, 0, 2],
        [1, 2, 0],
        [0, 1, 3]
    ],
    [
        [0, 0, 2],
        [1, 2, 0],
        [0, 1, 3],
        [2, 2, 1]
    ],
    [
        [1, 2, 0],
        [0, 1, 3],
        [2, 2, 1],
        [2, 0, 2]
    ]
]

It is relatively straightforward using a loop, but it gets extremely slow with several million values (instead of 6 in this example) in the initial array.

Is there a faster way to get to new_arr using Numpy primitives?

1 Answer 1

3

You can use NumPy, specifically this function (only NumPy >= 1.20.0):

from numpy.lib.stride_tricks import sliding_window_view

new_arr = sliding_window_view(arr, (n, arr.shape[1])).squeeze()
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way to achieve this using Numpy 1.19 ? For some reason Numpy >= 1.20 has dependency conflicts with TensorFlow.
sliding_window_view is a more user friendly substitute for numpy.lib.stride_tricks.as_strided introduced in numpy 1.20. Just use it with an extreme care.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.