numpy function to set elements of array to a value given a list of indices numpy function to set elements of array to a value given a list of indices numpy numpy

numpy function to set elements of array to a value given a list of indices


You can just give it a list of indices:

indices = [1, 4, 5, 6, 7]zero = numpy.zeros(10)zero[indices] = 42


If you have an ndarray:

>>> x = np.zeros((3, 3, 3))>>> y = [0, 9, 18]>>> xarray([[[ 0.,  0.,  0.],       [ 0.,  0.,  0.],       [ 0.,  0.,  0.]],      [[ 0.,  0.,  0.],       [ 0.,  0.,  0.],       [ 0.,  0.,  0.]],      [[ 0.,  0.,  0.],       [ 0.,  0.,  0.],       [ 0.,  0.,  0.]]])>>> np.put(x, y,  1)>>> xarray([[[ 1.,  0.,  0.],        [ 0.,  0.,  0.],        [ 0.,  0.,  0.]],       [[ 1.,  0.,  0.],        [ 0.,  0.,  0.],        [ 0.,  0.,  0.]],       [[ 1.,  0.,  0.],        [ 0.,  0.,  0.],        [ 0.,  0.,  0.]]])