0

I have numpy array of numbers in range 0-9, and I would like to convert the numbers to a 'flag' in the index of said number. Following code does exactly what I would like:

In [1]: import numpy as np

In [2]: a = np.array([5, 2, 7])

In [3]: b = np.zeros((3, 10))

In [4]: for i in range(a.shape[0]):
   ...:     b[i][a[i]] = 1
   ...:

In [5]: b
Out[5]:
array([[0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],
       [0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 1., 0., 0.]])

But I am wondering what is this conversion called, and is there a Numpy way to do this?

Toothery
  • 155
  • 1
  • 1
  • 10

1 Answers1

0

Try using np.arange:

b[np.arange(a.shape[0]), a] = 1
U13-Forward
  • 69,221
  • 14
  • 89
  • 114