添加一个额外的维度到arr2
:
arr1[:, :, range(25,26,1)] = arr2.reshape(arr2.shape + (1,))
在这里使用的更简单的符号range
:
arr1[:, :, 25:26)] = arr2.reshape(arr2.shape + (1,))
(and slice(25,26,1)
, or slice(25,26)
, 也可以工作;只是为了增加选项和可能的混淆。)
或者在 的末尾插入一个额外的轴arr2
:
arr1[..., 25:26] = arr2[..., np.newaxis]
(其中的...
意思是“尽可能多的维度”)。您也可以使用None
代替np.newaxis
; 后者可能更明确,但任何了解 NumPy 的人都会将其识别None
为插入额外的维度(轴)。
当然,您也可以arr2
从一开始就设置为 3 维:
arr2 = np.zeros([6,10,1])
请注意,从左侧使用时,广播确实有效:
>>> arr1 = np.zeros([50,6,10]) # Swapped ("rolled") dimensions
>>> arr2 = np.zeros([6,10])
>>> arr1[25:26, :, :] = arr2 # No need to add an extra axis
只是从右侧使用时它不起作用,就像在您的代码中一样。