沿轴和索引的 Numpy 数组分配

Numpy array assignment along axis and index

我有一个 3D 体积,我沿不同的轴修改切片。

for idx in range(len(self.volume)): 
    for axe in range(self.volume.ndim): # = range(3)
        slice_ = np.take(self.volume, idx, axis = axe)
        ''' Do something '''

(np.take 等同于写 self.volume[idx], self.volume[:, idx] 和 self.volume[:, :, idx])

最后,我想在我的体积中沿轴分配一个新切片:

    if axe == 0:
        self.volume[idx] = new_slice
    elif axe == 1:
        self.volume[:,idx] = new_slice
    else:
        self.volume[:,:,idx] = new_slice

这是我需要帮助的地方。我想不出更简洁的方法来完成这项任务。 (我想要像 np.take() 一样干净的东西)

我试过np.insert、np.insert_along_axis、np.put、np.put_along_axis...但我显然遗漏了一些东西出。

有什么想法吗? :)

祝你有美好的一天

可能有更优雅的解决方案,但以下应该可行:

s = [slice(None)]*self.volume.ndim
s[axe] = slice(idx,idx+1)
self.volume[tuple(s)] = np.expand_dims(new_slice, axe)

或者,您可以尝试:

self.volume  = np.swapaxes(self.volume, 0, axe)
self.volume[idx] = new_slice
self.volume  = np.swapaxes(self.volume, 0, axe)