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?

1
  • b[np.arange(3), a] = 1 Commented Oct 11, 2021 at 8:27

1 Answer 1

0

Try using np.arange:

b[np.arange(a.shape[0]), a] = 1 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.