Fernando Ribeiro
Fernando Ribeiro

Reputation: 43

How replace values from one numpy array by other array with indices

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.

Upvotes: 2

Views: 1803

Answers (1)

mathfux
mathfux

Reputation: 5949

Try advanced indexing:

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

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

Upvotes: 3

Related Questions