Jud*_*udy 4 python arrays numpy
我会使用NumPy或本机函数将2d数组转换为前一行的3d.
输入:
[[1,2,3],
[4,5,6],
[7,8,9],
[10,11,12],
[13,14,15]]
Run Code Online (Sandbox Code Playgroud)
输出:
[[[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]]]
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮忙吗?我在网上搜索了一段时间,但无法得到答案.
方法#1
一种方法np.lib.stride_tricks.as_strided使我们view进入输入2D数组,因此不再占用内存空间 -
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))
Run Code Online (Sandbox Code Playgroud)
样本输入,输出 -
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]]])
Run Code Online (Sandbox Code Playgroud)
方法#2
或者,broadcasting在生成所有行索引时更容易一点-
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]]])
Run Code Online (Sandbox Code Playgroud)