请考虑以下几点:
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
答案 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