Charles B
Charles B

Reputation: 95

Comparing arrays and adding to different elements?

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

I want to compare these two arrays element wise and I want to add n to only those elements of z that are different to those of x.

Answer should be:

z = [2, 2, 3, 5]

Upvotes: 2

Views: 84

Answers (2)

Divakar
Divakar

Reputation: 221614

Get a mask, scale it and do in-place add -

z += n*(z!=x)

Another approach using just the mask -

z[z!=x] += n

Sample runs -

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

Runtime test -

Approaches -

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

Timings -

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

Upvotes: 0

Allen Qin
Allen Qin

Reputation: 19957

Another solution using 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])

Upvotes: 2

Related Questions