如果等于另一个数组,则替换数组的值

时间:2019-08-14 17:28:12

标签: python arrays numpy

如果两个数组相等,我想将特定的数组索引从数组A复制到数组B

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]])

现在A[:,0:3] == B[:,0:3]是否要替换B[:,3] with A[:,3]

喜欢

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

1 个答案:

答案 0 :(得分:1)

您可以将np.copytowhere关键字一起使用:

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]])