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

后端 未结 2 1229
广开言路
广开言路 2020-12-31 05:30

I\'m looking for a numpy function that will do the equivalent of:

indices = set([1, 4, 5, 6, 7])
zero    = numpy.zeros(10)
for i in indices:
    zero[i] = 42         


        
2条回答
  •  天命终不由人
    2020-12-31 05:52

    If you have an ndarray:

    >>> x = np.zeros((3, 3, 3))
    >>> y = [0, 9, 18]
    >>> x
    array([[[ 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)
    >>> x
    array([[[ 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.]]])
    

提交回复
热议问题