0

I have an array of some given size e.g 4x4 with all zeros,

a = np.zeros((4,4))

and I want to put 1 in each row at the column index given by another array

b = np.array([0,1,2,1])

so the resulted array should look like this,

a = 
1   0   0   0
0   1   0   0
0   0   1   0
0   1   0   0

How can I do this for a large array of size (mxn) given b of size (mx1).

Thank You and Best Regards,

2 Answers 2

3

You can use this simple way of indexing 2D array:

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

Comments

0

Loop through rows in a and values in b using zip():

for row, idx in zip(a, b):
    row[idx] = 1

1 Comment

Thank you for your answer, but can it be achieved without for loop in a more efficient manner?

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.