Reputation: 1704
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.
Upvotes: 2
Views: 70
Reputation: 16147
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]]]])
Upvotes: 3