2

Can someone explain to me how to accomplish this?

[
    [1, 2, 9, 10, 17, 18],
    [3, 4, 11, 12, 19, 20],
    [5, 6, 13, 14, 21, 22],
    [7, 8, 15, 16, 23, 24]
]

=>

[
    [
        [1, 2],
        [3, 4]
    ],
    [
        [2, 9],
        [4, 11]
    ],
    [
        [9, 10],
        [11, 12]
    ],
    [
        [10, 17],
        [12, 19]
    ],
    [
        [17, 18],
        [19, 20]
    ]
],
[
    [
        [5, 6],
        [7, 8]
    ],
    [
        [6, 13],
        [8, 15]
    ]
    ...
]

I tried to use numpy.split but this allows only for non-overlapping subarrays.

Basically these are all subarrays of size (2,2) where an imaginary window is moved from top left to bottom right by one column each time.

1 Answer 1

3

As long as you have numpy version 1.20.0 or higher, you can use sliding window view to pass in a window size and get the the form you are looking for.

import numpy as np
from numpy.lib.stride_tricks import sliding_window_view
arr = np.array([
    [1, 2, 9, 10, 17, 18],
    [3, 4, 11, 12, 19, 20],
    [5, 6, 13, 14, 21, 22],
    [7, 8, 15, 16, 23, 24]
])

sliding_window_view(arr,(2,2))

Output

array([[[[ 1,  2],
         [ 3,  4]],

        [[ 2,  9],
         [ 4, 11]],

        [[ 9, 10],
         [11, 12]],

        [[10, 17],
         [12, 19]],

        [[17, 18],
         [19, 20]]],


       [[[ 3,  4],
         [ 5,  6]],

        [[ 4, 11],
         [ 6, 13]],

        [[11, 12],
         [13, 14]],

        [[12, 19],
         [14, 21]],

        [[19, 20],
         [21, 22]]],


       [[[ 5,  6],
         [ 7,  8]],

        [[ 6, 13],
         [ 8, 15]],

        [[13, 14],
         [15, 16]],

        [[14, 21],
         [16, 23]],

        [[21, 22],
         [23, 24]]]])
Sign up to request clarification or add additional context in comments.

Comments

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.