【问题标题】:Transform 2D array to a 3D array with overlapping strides将 2D 数组转换为具有重叠步幅的 3D 数组
【发布时间】:2017-08-18 04:15:21
【问题描述】:

我会使用 NumPy 或本机函数将 2d 数组转换为具有前几行的 3d。

输入:

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

有人可以帮忙吗? 我在网上搜索了一段时间,但没有得到答案。

【问题讨论】:

  • 我想我明白你想要什么,但这与你在问题中写的没有任何关系。到目前为止你做了什么?请发布您的代码。
  • @DYZ 不确定混乱在哪里。 OP 已经列出了 2D 输入和预期 3D 输出,其中包含从 2D 输入中提取的行,这些行是当前行和它们之前的行,再次在预期输出中列出。

标签: python arrays numpy


【解决方案1】:

方法#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))

样本输入、输出-

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 会更容易一些 -

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

【讨论】:

    【解决方案2】:

    列表理解怎么样?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      • 2017-07-26
      • 1970-01-01
      • 2021-12-29
      • 2013-08-21
      • 1970-01-01
      相关资源
      最近更新 更多