简体   繁体   English

将2D数组转换为具有重叠步幅的3D数组

[英]Transform 2D array to a 3D array with overlapping strides

I would convert the 2d array into 3d with previous rows by using NumPy or native functions. 我会使用NumPy或本机函数将2d数组转换为前一行的3d。

Input: 输入:

[[1,2,3],
 [4,5,6],
 [7,8,9],
 [10,11,12],
 [13,14,15]]

Output: 输出:

[[[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. 我在网上搜索了一段时间,但无法得到答案。

Approach #1 方法#1

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 - 一种使用np.lib.stride_tricks.as_strided方法,它为我们提供了输入2D数组的view ,因此不再占用内存空间 -

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

Sample input, output - 样本输入,输出 -

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

Approach #2 方法#2

Alternatively, a bit easier one with broadcasting upon generating all of row indices - 或者,在生成所有行索引时使用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]]])

How about a list comprehension? 列表理解怎么样?

In [144]: np.array([l[i:i + 3][::-1] for i in range(0, len(l) - 2)])
Out[144]: 
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]]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM