跨步将2D数组转换为3D数组 [英] Transform 2D array to a 3D array with overlapping strides
本文介绍了跨步将2D数组转换为3D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以通过使用NumPy或本机函数将2d数组转换为具有先前行的3d.
I would convert the 2d array into 3d with previous rows by using NumPy or native functions.
输入:
[[1,2,3],
[4,5,6],
[7,8,9],
[10,11,12],
[13,14,15]]
输出:
[[[7,8,9], [4,5,6], [1,2,3]],
[[10,11,12], [7,8,9], [4,5,6]],
[[13,14,15], [10,11,12], [7,8,9]]]
任何人都可以帮忙吗? 我已经在网上搜索了一段时间,但找不到答案.
Any one can help? I have searched online for a while, but cannot got the answer.
推荐答案
方法1
使用 np.lib.stride_tricks.as_strided
的一种方法view
放入输入2D
数组中,因此不再占用存储空间-
One approach with np.lib.stride_tricks.as_strided
that gives us a view
into the input 2D
array and as such doesn't occupy anymore of the memory space -
L = 3 # window length for sliding along the first axis
s0,s1 = a.strides
shp = a.shape
out_shp = shp[0] - L + 1, L, shp[1]
strided = np.lib.stride_tricks.as_strided
out = strided(a[L-1:], shape=out_shp, strides=(s0,-s0,s1))
样本输入,输出-
In [43]: a
Out[43]:
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15]])
In [44]: out
Out[44]:
array([[[ 7, 8, 9],
[ 4, 5, 6],
[ 1, 2, 3]],
[[10, 11, 12],
[ 7, 8, 9],
[ 4, 5, 6]],
[[13, 14, 15],
[10, 11, 12],
[ 7, 8, 9]]])
方法2
或者,使用 broadcasting
在生成所有行索引时-
Alternatively, a bit easier one with broadcasting
upon generating all of row indices -
In [56]: a[range(L-1,-1,-1) + np.arange(shp[0]-L+1)[:,None]]
Out[56]:
array([[[ 7, 8, 9],
[ 4, 5, 6],
[ 1, 2, 3]],
[[10, 11, 12],
[ 7, 8, 9],
[ 4, 5, 6]],
[[13, 14, 15],
[10, 11, 12],
[ 7, 8, 9]]])
这篇关于跨步将2D数组转换为3D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文