3

i want to assign an array that specific (row, col) with value 1

here is my code:

fl = np.zeros((5, 3))
labels = np.random.random_integers(0, 2, (5, 1))
for i in range(5):
    fl[i, labels[i]] = 1

is there some shortcut for the process?

2 Answers 2

1

Here is another way to do it:

import numpy as np
fl = np.zeros((5, 3))
labels = np.random.random_integers(0, 2, 5)
fl[range(0, 5), labels] = 1

And it will produce this output:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

You can use labels array as a boolean array with fl.shape as shape. Try:

import numpy as np
fl = np.zeros((5, 3))
labels = np.random.random_integers(0, 1, fl.shape).astype(bool)
fl[labels] = 1

And here is how the array of boolean's in labels and result will look like:

>>> labels
array([[False,  True, False],
   [ True,  True, False],
   [False,  True,  True],
   [ True,  True,  True],
   [ True, False, False]], dtype=bool)

>>> fl
array([[ 0.,  1.,  0.],
   [ 1.,  1.,  0.],
   [ 0.,  1.,  1.],
   [ 1.,  1.,  1.],
   [ 1.,  0.,  0.]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.