Reputation: 571
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 numpy as np
A = np.array([[1,2,3],[3,4,5],[5,6,7],[0,8,9],[3,7,5]])
B = np.array([0,2,1,2,0])
C = np.array([8,9,6,5,4])
for i in range(5):
A[i, B[i]] = C[i]
print ("FOR", A)
A = np.array([[1,2,3],[3,4,5],[5,6,7],[0,8,9],[3,7,5]])
A[:,B[:]] = C[:]
print ("Vectorized, A", A)
Output:
FOR [[8 2 3]
[3 4 9]
[5 6 7]
[0 8 5]
[4 7 5]]
Vectorized, A [[4 6 5]
[4 6 5]
[4 6 5]
[4 6 5]
[4 6 5]]
The for loop and vectorization gave different results. I am unsure how to vectorize this for loop using Numpy.
Upvotes: 2
Views: 1023
Reputation: 107337
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
Upvotes: 1