替换 3d numpy 数组中的值

Replace values in a 3d numpy array

有这两个 numpy 数组:

a = np.array([
    [
        [1,2,3,0,0],
        [4,5,6,0,0],
        [7,8,9,0,0]
    ],
    [
        [1,3,5,0,0],
        [2,4,6,0,0],
        [1,1,1,0,0]
    ]
])

b = np.array([
    [
        [1,2],
        [2,3],
        [3,4]
    ],
    [
        [4,1],
        [5,2],
        [6,3]
    ]
])

形状:

"a" shape: (2, 3, 5), "b" shape: (2, 3, 2)

我想用数组 b 中的元素替换数组 a 中的最后两个元素,例如

c = np.array([
    [
        [1,2,3,1,2],
        [4,5,6,2,3],
        [7,8,9,3,4]
    ],
    [
        [1,3,5,4,1],
        [2,4,6,5,2],
        [1,1,1,6,3]
    ]
])

但是,np.hstack((a[:,:,:-2], b)) 抛出值错误:

all the input array dimensions except for the concatenation axis must match exactly

总的来说,它看起来不像是正确使用的函数。附加也不起作用。

numpy 中是否有方法可以做到这一点,或者我是否需要使用 for 循环遍历数组并手动操作它们?

您可以像这样使用直接索引:

a[:, :, 3:] = b

Non-overwriting方法:

  • a[:,:,-2:] 在末尾获取零;使用 a[:,:,:3].

  • 根据documentationnp.hstack(x)等价于np.concatenate(x, axis=1)。因为你想加入最里面行的矩阵,你应该使用 axis=2.

代码:

>>> np.concatenate((a[:,:,:3], b), axis=2)
array([[[1, 2, 3, 1, 2],
        [4, 5, 6, 2, 3],
        [7, 8, 9, 3, 4]],

       [[1, 3, 5, 4, 1],
        [2, 4, 6, 5, 2],
        [1, 1, 1, 6, 3]]])