[英]How to split a 2D array into a list of smaller 2D arrays with overlapping? Python
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.我想将二维数组 x * y 拆分为一些较小的二维 arrays,它们是 N * N 重叠并将这些较小的 arrays 作为值存储在字典中,键将是较大数组中左上角项目的索引。
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.我有使用 numpy 将其拆分为较小的 arrays 而不重叠的想法,但我不知道这种情况。
How can this be done?如何才能做到这一点? Full of thanks!
满满的感谢!
The operation you want to do is a sliding window .你要做的操作是滑动 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]]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.