如何使用填充0重塑Numpy数组

时间:2019-06-27 17:50:03

标签: python arrays numpy reshape

我有一个类似的Numpy数组

array([1, 2, 3, 4, 5, 6, 7, 8])

我想将其重塑为数组

array([[5, 0, 0, 6],
       [0, 1, 2, 0],
       [0, 3, 4, 0],
       [7, 0, 0, 8]])

更具体地说,我正在尝试重塑2D numpy数组以获取3D Numpy数组

array([[ 1,  2,  3,  4,  5,  6,  7,  8],
       [ 9, 10, 11, 12, 13, 14, 15, 16],
       [17, 18, 19, 20, 21, 22, 23, 24],
       ...
       [ 9, 10, 11, 12, 13, 14, 15, 16],
       [89, 90, 91, 92, 93, 94, 95, 96]])

到看起来像的numpy数组

array([[[ 5,  0,  0,  6],
        [ 0,  1,  2,  0],
        [ 0,  3,  4,  0],
        [ 7,  0,  0,  8]],

       [[13,  0,  0, 14],
        [ 0,  9, 10,  0],
        [ 0, 11, 12,  0],
        [15,  0,  0, 16]],
       ...
       [[93,  0,  0, 94],
        [ 0, 89, 90,  0],
        [ 0, 91, 92,  0],
        [95,  0,  0, 96]]])

是否有使用numpy功能(尤其是矢量化)来实现此目的的有效方法?

1 个答案:

答案 0 :(得分:3)

我们可以利用slicing-

def expand(a): # a is 2D array      
    out = np.zeros((len(a),4,4),dtype=a.dtype)
    out[:,1:3,1:3] = a[:,:4].reshape(-1,2,2)
    out[:,::3,::3] = a[:,4:].reshape(-1,2,2)
    return out

好处是记忆力和性能。效率,因为只有输出会占用存储空间。由于在输入和输出上进行了切片,因此可以使用视图进行操作。

样品运行-

2D输入:

In [223]: a
Out[223]: 
array([[ 1,  2,  3,  4,  5,  6,  7,  8],
       [ 9, 10, 11, 12, 13, 14, 15, 16]])

In [224]: expand(a)
Out[224]: 
array([[[ 5,  0,  0,  6],
        [ 0,  1,  2,  0],
        [ 0,  3,  4,  0],
        [ 7,  0,  0,  8]],

       [[13,  0,  0, 14],
        [ 0,  9, 10,  0],
        [ 0, 11, 12,  0],
        [15,  0,  0, 16]]])

一维输入(使用None输入2D扩展输入):

In [225]: a = np.array([1, 2, 3, 4, 5, 6, 7, 8])

In [226]: expand(a[None])
Out[226]: 
array([[[5, 0, 0, 6],
        [0, 1, 2, 0],
        [0, 3, 4, 0],
        [7, 0, 0, 8]]])