切片数组,但在Python中重叠间隔

问题描述 投票:1回答:1

我的数据中有3D数组。我只是想在Python中以重叠间隔将2D数组2切2乘2。

这是2D的一个例子。

a = [1, 2, 3, 4;
     5, 6, 7, 8]

此外,这是我在2×2切片后的预期。

[1, 2;  [2, 3;  [3, 4;
 5, 6]   6, 7]   7, 8]

在3D中,

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

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

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

像这样,(也许不完全是......)

 [1, 2   [2, 3
  4, 5]   5, 6]       ...
 [1, 2   [2, 3
  4, 5]   5, 6] 

我认为,通过使用np.split,我可以切片数组,但没有重叠。请给我一些有用的提示。

python arrays python-3.x slice
1个回答
1
投票

你应该看看numpy.ndarray.stridesnumpy.lib.stride_tricks

遍历数组时每个维度中的字节元组。数组(i[0], i[1], ..., i[n])中元素a的字节偏移量为:

offset = sum(np.array(i) * a.strides)

另见numpy documentation

遵循使用步幅的2D示例:

x = np.arange(20).reshape([4, 5])
>>> x
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

>>> from numpy.lib import stride_tricks
>>> stride_tricks.as_strided(x, shape=(3, 2, 5),
                                strides=(20, 20, 4))
...
array([[[  0,  1,  2,  3,  4],
        [  5,  6,  7,  8,  9]],

       [[  5,  6,  7,  8,  9],
        [ 10, 11, 12, 13, 14]],

       [[ 10, 11, 12, 13, 14],
        [ 15, 16, 17, 18, 19]]])

另请参阅此示例所在的Stackoverflow上的question,以增加您的理解。

© www.soinside.com 2019 - 2024. All rights reserved.