18

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
involucelate
  • 273
  • 2
  • 3
  • 7

2 Answers2

30

You can just give it a list of indices:

indices = [1, 4, 5, 6, 7]
zero = numpy.zeros(10)
zero[indices] = 42
stranac
  • 26,638
  • 5
  • 25
  • 30
4

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.]]])
Andre Holzner
  • 18,333
  • 6
  • 54
  • 63
Sun
  • 2,658
  • 6
  • 28
  • 33