替换n维numpy数组中特定轴索引的元素

Replace elements of particular axis index in n-dimensional numpy array

给定一个 n 维 numpy 数组。现在给出了一个轴和相应的索引。该特定轴索引中的所有元素都应替换为给定值。 三维数组示例:

>>a = np.ones((2,2,2))
array([[[ 1.,  1.],
        [ 1.,  1.]],

        [[ 1.,  1.],
        [ 1.,  1.]]])

给定轴=1,索引=0。此轴索引中的所有元素都必须为零。

>>a
array([[[ 0.,  0.],
        [ 1.,  1.]],

       [[ 0.,  0.],
        [ 1.,  1.]]])

你可以做 a[:,0,:] = 0 并得到你的输出,在 a[:,0,:] 你 select index = 0 of the axis=1 并且你将值设置为 0 在所有其他轴

使用swapaxes:

a.swapaxes(0, axis)[index] = value

示例:

>>> import numpy as np
>>> a = np.zeros((2,3,4))
>>> a.swapaxes(0, 1)[2] = 3
>>> a
array([[[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [3., 3., 3., 3.]],

       [[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [3., 3., 3., 3.]]])