1

What would be the simplest (fastest) way to take as input the following :

M=np.zeros((2,5))  
values=[a,b,c] #a,b and c are integers  
indices=[(1,2,4),(0,2,4)]

and have as an output :

M=[[0,a,b,0,c],[a,0,b,0,c]]
5
  • 1
    you mean M=np.zeros((2,5))? Commented Feb 23, 2021 at 15:35
  • 1
    So in your indices, the numbers in the tuples represent where the values go? (example: (0,2,4) -> [a, 0 , b, 0 ,c] correct?) Commented Feb 23, 2021 at 15:38
  • What do you mean by "simplest"? Shortest code? Most idiomatic? Least brainpower used to come up with a solution? Commented Feb 23, 2021 at 15:41
  • @Reti43 by simplest I mean fastest Commented Feb 23, 2021 at 15:49
  • @jasonmzx yes that is the case Commented Feb 23, 2021 at 15:50

1 Answer 1

2

try indexing

M = np.zeros((2,5))
values = [7,8,9]   
indices = np.array([[1,2,4],[0,2,4]])

M[np.arange(M.shape[0])[:,None],indices] = values

print(M)
[[0. 7. 8. 0. 9.]
 [7. 0. 8. 0. 9.]]
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.