2

I have two arrays and one list with indices

Array source (array 01):

x = np.array([[1,2,3], [4,5,6], [7,8,9]])
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

Array with new values (array 02):

y = np.array([11, 22, 33])
array([11, 22, 33])

and a list with indices

a = [1,2,1]
[1, 2, 1]

I need to replace the values of array 02 in array 01 based on indices

The return expected:

array([[1, 11, 3],
       [4, 5, 22],
       [7, 33, 9]])

How to do this without loop?

Thanks in advance.

2

1 Answer 1

3

Try advanced indexing:

x[np.arange(len(x)), a] = y

I found also this tutorial easier for me than official documentation.

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

1 Comment

@Fernando this is because Python loops are slow and numpy actions are actually internal loops done in C level.

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.