Reputation: 93
I have a 2D mxn array A and another 2D qxp array B. I want to assign value of 1 to A at each coordinate listed in B.
I know that I could firstly get the length of b at axis=0, and write a loop to do it such like A[B[i,0]][b[i,1]] = 1; but i am working on a big dataset, I want to see if there is any way to do this without a for loop.
Upvotes: 0
Views: 164
Reputation: 1120
You can directly assign the values by passing the columns of B as indices of A. You don't need to loop through the rows of B.
A[B[:,0],B[:,1]]=1
Here's a more detailed example
A=np.zeros((4,4))
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
B=np.array([[2,1],[2,2],[0,2],[3,0]])
array([[2, 1],
[2, 2],
[0, 2],
[3, 0]])
# directly pass each of the columns of B as indices of A
A[B[:,0],B[:,1]] = 1
print(A)
array([[0., 0., 1., 0.],
[0., 0., 0., 0.],
[0., 1., 1., 0.],
[1., 0., 0., 0.]])
Upvotes: 1