比较数组并添加到不同的元素?

时间:2017-05-04 21:05:52

标签: python arrays numpy elementwise-operations

z = np.array([1, 2, 3, 4]) 
x = np.array([4, 2, 3, 5])
n = 1

我想比较这两个数组元素,我想只将n添加到z的那些与x的元素不同的元素。

答案应该是:

z = [2, 2, 3, 5]

2 个答案:

答案 0 :(得分:3)

使用np.where

的另一种解决方案
#np.where checks if the condition is met, if yes set the value to z, otherwise z+n.
np.where(z==x, z,z+n)
Out[1257]: array([2, 2, 3, 5])

答案 1 :(得分:1)

获取面具,缩放并进行就地添加 -

z += n*(z!=x)

另一种只使用面具的方法 -

z[z!=x] += n

样品运行 -

In [176]: z = np.array([1, 2, 3, 4]) 
     ...: x = np.array([4, 2 ,3 ,5])
     ...: n = 1
     ...: 

In [177]: z += n*(z!=x)

In [178]: z
Out[178]: array([2, 2, 3, 5])

In [179]: z = np.array([1, 2, 3, 4])

In [180]: z[z!=x] += n

In [181]: z
Out[181]: array([2, 2, 3, 5])

运行时测试 -

方法 -

def app1(z, x, n):
    z += n*(z!=x)
    return z

def app2(z, x, n):
    z[z!=x] += n
    return z

def where_based(z, x, n): # @Allen's soln
    z = np.where(z==x, z,z+n)
    return z

计时 -

In [205]: z = np.random.randint(0,9,(1000000))
     ...: x = np.random.randint(0,9,(1000000))
     ...: n = 5
     ...: 
     ...: zc1 = z.copy()
     ...: zc2 = z.copy()
     ...: zc3 = z.copy()
     ...: 

In [206]: %timeit app1(zc1, x, n)
100 loops, best of 3: 2.82 ms per loop

In [207]: %timeit app2(zc2, x, n)
100 loops, best of 3: 7.95 ms per loop

In [208]: %timeit where_based(zc3, x, n)
100 loops, best of 3: 4.51 ms per loop