Home > Software engineering >  How to split a 2D array into a list of smaller 2D arrays with overlapping? Python
How to split a 2D array into a list of smaller 2D arrays with overlapping? Python

Time:11-21

I want to split a 2D array x * y into some smaller 2D arrays which are N * N with overlapping and store these smaller arrays as values in a dictionary, the key will be the index of the top-left item in the larger array.

From

[[1,2,3,4],
 [5,6,7,8],
 [9,10,11,12]]

To

{(0,0):[[1,2],[5,6]], (0,1):[[2,3],[6,7]], (0,2):[[3,4],[7,8]], (1,0):[[5,6],[9,10]], (1,1):[[6,7],[10,11]], (1,2):[[7,8],[11,12]]}

I have idea of splitting it into smaller arrays without overlapping using numpy, but I have no idea of this case.

How can this be done? Full of thanks!

CodePudding user response:

The operation you want to do is a sliding window.

import numpy as np

A = np.array([
    [1,  2,  3,  4],
    [5,  6,  7,  8],
    [9,  10, 11, 12]
])

result = dict(zip(
    [(i, j) for i in range(2) for j in range(3)],
    np.lib.stride_tricks.sliding_window_view(A, (2, 2)).reshape(-1, 2, 2).tolist()
))

# {(0, 0): [[1, 2], [5, 6]], (0, 1): [[2, 3], [6, 7]], (0, 2): [[3, 4], [7, 8]], (1, 0): [[5, 6], [9, 10]], (1, 1): [[6, 7], [10, 11]], (1, 2): [[7, 8], [11, 12]]}
  • Related