沿给定轴替换值

时间:2019-03-06 21:25:06

标签: python numpy

请考虑以下几点:

  • 一个numpy的超立方体,例如x = np.random.rand(8, 8, 8, 8)
  • 尺寸索引,例如dim = 1
  • 替换数组,例如y = np.random.rand(8)

如何替换给定维的所有值?

即,我能做得更好吗?

if dim == 0:
    x[0,:,:,:] = y
elif dim == 1:
    x[:,0,:,:] = y
elif dim == 2:
    x[:,:,0,:] = y
elif dim == 3:
    x[:,:,:,0] = y
else:
    throw

2 个答案:

答案 0 :(得分:0)

您可以通过生成器表达式创建索引元组:

x[tuple(0 if i == dim else slice(None) for i in range(4))] = y

更详细的版本:

index = [slice(None)] * len(x.shape)
index[dim] = 0
x[tuple(index)] = y

答案 1 :(得分:0)

您可以将光轴向前移动:

np.moveaxis(x, dim, 0)[0] = y