user2963882
user2963882

Reputation: 627

Replace array value if equal to another array

I want to copy over a specific array index from array A to array B if both arrays are equal

A = np.random.randint(0, 5, size=(5, 4))
B = a.copy()
B[0,0] = 10
B[:,3] = 999

B:

array([[ 10,   0,   4, 999],
       [  4,   3,   2, 999],
       [  1,   4,   3, 999],
       [  1,   3,   1, 999],
       [  3,   1,   1, 999]])

A:

array([[0, 0, 4, 3],
       [4, 3, 2, 2],
       [1, 4, 3, 2],
       [1, 3, 1, 4],
       [3, 1, 1, 3]])

now if A[:,0:3] == B[:,0:3] I want to replace B[:,3] with A[:,3]

like

array([[ 10,   0,   4, 999],
       [  4,   3,   2, 2],
       [  1,   4,   3, 2],
       [  1,   3,   1, 4],
       [  3,   1,   1, 3]])

Upvotes: 0

Views: 50

Answers (1)

Paul Panzer
Paul Panzer

Reputation: 53029

You can use np.copyto with the where keyword:

np.copyto(B[:,3],A[:,3],where=(A[:,:3]==B[:,:3]).all(1))
B
# array([[ 10,   0,   4, 999],
#        [  4,   3,   2,   2],
#        [  1,   4,   3,   2],
#        [  1,   3,   1,   4],
#        [  3,   1,   1,   3]])

Upvotes: 1

Related Questions