Python:沿着不同的行将2D数组插入3D NumPy数组

时间:2019-08-27 11:35:12

标签: python numpy multidimensional-array

我正在尝试将大小为[2, 2]的2D数组插入大小为[2, 3, 2]的3D数组中。对于3D阵列的每个页面(轴= 0),插入2D阵列的位置(读取:行号)可能会有所不同。我尝试使用np.insert函数。但是,我正在努力……

import numpy as np

arr = np.arange(12).reshape(2, 3, 2)

arr
array([[[ 0,  1],
        [ 2,  3],
        [ 4,  5]],

       [[ 6,  7],
        [ 8,  9],
        [10, 11]]])

row_number_before_insertion = [1, 2]
val_to_insert = (np.ones(4) * 100).reshape(2,2)
arr_expanded = np.insert(arr, row_number_before_insertion , val_to_insert, axis=1)

arr_expanded
array([[[  0,   1],
        [100, 100],
        [  2,   3],
        [100, 100],
        [  4,   5]],

       [[  6,   7],
        [100, 100],
        [  8,   9],
        [100, 100],
        [ 10,  11]]])

我实际上正在寻找以下结果:

arr_expanded
array([[[  0,   1],
        [100, 100],
        [100, 100],
        [  2,   3],
        [  4,   5]],

       [[  6,   7],
        [  8,   9],
        [100, 100],
        [100, 100],
        [ 10,  11]]])

2 个答案:

答案 0 :(得分:1)

这是一个基于数组分配和masking-

from skimage.util.shape import view_as_windows

def insert_into_arr(arr, row_number_before_insertion, val_to_insert):
    ma,na,ra = arr.shape
    L = len(val_to_insert)
    N = len(row_number_before_insertion)

    out = np.zeros((ma,na+L,ra),dtype=arr.dtype)
    mask = np.ones(out.shape, dtype=bool)

    w = view_as_windows(out,(1,L,1))[...,0,:,0]
    w[np.arange(N), row_number_before_insertion] = val_to_insert.T

    wm = view_as_windows(mask,(1,L,1))[...,0,:,0]
    wm[np.arange(N), row_number_before_insertion] = 0

    out[mask] = arr.ravel()
    return out

样品运行-

In [44]: arr
Out[44]: 
array([[[ 0,  1],
        [ 2,  3],
        [ 4,  5]],

       [[ 6,  7],
        [ 8,  9],
        [10, 11]]])

In [45]: row_number_before_insertion
Out[45]: array([1, 2])

In [46]: val_to_insert
Out[46]: 
array([[784, 659],
       [729, 292],
       [935, 863]])

In [47]: insert_into_arr(arr, row_number_before_insertion, val_to_insert)
Out[47]: 
array([[[  0,   1],
        [784, 659],
        [729, 292],
        [935, 863],
        [  2,   3],
        [  4,   5]],

       [[  6,   7],
        [  8,   9],
        [784, 659],
        [729, 292],
        [935, 863],
        [ 10,  11]]])

另一个有repeatmasking的人-

def insert_into_arr_v2(arr, row_number_before_insertion, val_to_insert):  
    ma,na,ra = arr.shape
    r = row_number_before_insertion
    L = len(val_to_insert)
    M = na+L

    out = np.zeros((ma,na+L,ra),dtype=arr.dtype)

    idx = ((r + M*np.arange(len(r)))[:,None] + np.arange(L)).ravel()
    out.reshape(-1,ra)[idx] =np.repeat(val_to_insert[None],ma,axis=0).reshape(-1,ra)

    mask = np.isin(np.arange(ma*(na+L)),idx, invert=True)
    out.reshape(-1,ra)[mask] = arr.reshape(-1,ra)
    return out

答案 1 :(得分:0)

这是使用{ "productId":5 }, { "productId":7 }, { "productId":1 }, { "productId":4 }, { "productId":6 }, { "productId":2 } 的解决方案:

vstack