Skip to content Skip to sidebar Skip to footer

Vectorized Update Numpy Array Using Another Numpy Array Elements As Index

Let A,C and B be numpy arrays with the same number of rows. I want to update 0th element of A[0], 2nd element of A[1] etc. That is, update B[i]th element of A[i] to C[i] import num

Solution 1:

The reason that your approach doesn't work is that you're passing the whole B as the column index and replace them with C instead you need to specify both row index and column index. Since you just want to change the first 4 rows you can simply use np.arange(4) to select the rows B[:4] the columns and C[:4] the replacement items.

In [26]: A[np.arange(4),B[:4]] = C[:4]

In [27]: A
Out[27]: 
array([[8, 2, 3],
       [3, 4, 9],
       [5, 6, 7],
       [0, 8, 5],
       [3, 7, 5]])

Note that if you wanna update the whole array, as mentioned in comments by @Warren you can use following approach:

A[np.arange(A.shape[0]), B] = C

Post a Comment for "Vectorized Update Numpy Array Using Another Numpy Array Elements As Index"