我的数据中有 3D 数组。我只想在 Python 中以重叠间隔对 3D 数组进行 2 × 2 × 2 的切片。
这是 2D 的示例。
a = [1, 2, 3, 4;
5, 6, 7, 8]
此外,这也是我将数组切成 2 x 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,我可以对数组进行切片,但不会重叠。请给我一些有用的提示。
最佳答案
You should have a look at
numpy.ndarray.strides
andnumpy.lib.stride_tricks
遍历数组时在每个维度中步进的字节元组。
数组 a
中元素 (i[0], i[1], ..., i[n])
的字节偏移量为:
offset = sum(np.array(i) * a.strides)
另请参阅 numpy documentation
Following a 2D example using strides:
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]]])
另请参阅此 question在 Stackoverflow 上(此示例来自此处),以加深您的理解。
关于python - 切片数组,但 Python 中重叠间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54890736/