python - numpy:用不同的起点分割数组

标签 python numpy

有人可以向我解释如何实现这一目标吗?

[
    [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]
    ]
    ...
]

我尝试使用numpy.split,但这仅允许非重叠子数组。

基本上,这些都是大小为 (2,2) 的子数组,其中一个假想窗口每次从左上角移动到右下角一列。

最佳答案

只要你有 numpy 版本1.20.0或更高版本,你就可以使用滑动窗口 View 传入窗口大小并获取你正在查看的表单对于。

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))

输出

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]]]])

关于python - numpy:用不同的起点分割数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69800114/

相关文章:

python - 多序列互相关避免for循环

Python 评估多项式回归

python - 带有 gettext 的 Cython

python - 使用 CRUD 的 AJAX 表单提交

python - 使用 Python 使用其 PID 捕获 Linux 进程的标准输出

python - Pandas 列对象分桶值提取

python - 优化音频 DSP 程序的 numpy 计算

python - 你如何从keras中的图像Batchdataset输出图像

python - 点击图片无效

python - 在优化方法中将 numpy ndarray 转换为元组的元组