1

Is there a numpy way to do the below without using a loop?

A = np.array([[1,1],[2,2],[3,3],[4,4],[5,5]])
I = np.array([0, 1, 0, 1, 1])
V = np.array([6, 6, 6, 6, 6])

I want to update A such that it has 6 in the corresponding index specified by I. So A becomes ...

A = np.array([[6,1],[2,6],[6,3],[4,6],[5,6]])

Tried the following, but they did not work..

A[I] = V
A[:,I] = V

1 Answer 1

1

Try: A[np.arange(len(A)), I] = V:

In [15]: import numpy as np                                                                                              

In [16]: A = np.array([[1,1],[2,2],[3,3],[4,4],[5,5]])                                                                   

In [17]: I = np.array([0, 1, 0, 1, 1])                                                                                   

In [18]: V = np.array([6, 6, 6, 6, 6])                                                                                   

In [19]: A[np.arange(len(A)), I] = V                                                                                     

In [20]: A                                                                                                               
Out[20]: 
array([[6, 1],
       [2, 6],
       [6, 3],
       [4, 6],
       [5, 6]])
Sign up to request clarification or add additional context in comments.

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.