【问题标题】:Numpy array assignment along axis and index沿轴和索引的 Numpy 数组分配
【发布时间】:2021-07-19 08:56:46
【问题描述】:

我有一个 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...但我显然遗漏了一些东西。

有什么想法吗? :)

祝你有美好的一天

【问题讨论】:

    标签: python numpy numpy-ndarray


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 您建议的第一种方法不起作用,我有这个错误:ValueError:无法将输入数组从形状(512,512)广播到形状(512,1,512)。第二种方法也不起作用,因为我有 3 个轴,并且只交换 2 个轴会影响音量。
    • 我编辑了第一个方法,现在应该可以了。至于第二个,只要您在分配后交换轴,它就应该起作用。
    • 现在可以使用第一种方法。谢谢!
    猜你喜欢
    • 2021-07-20
    • 2012-01-29
    • 2019-11-18
    • 1970-01-01
    • 2013-04-19
    • 2018-10-12
    • 2017-03-27
    • 2017-06-03
    • 1970-01-01
    相关资源
    最近更新 更多