2
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]
Divakar
  • 218,885
  • 19
  • 262
  • 358
Charles B
  • 95
  • 3
  • 14
  • Can you restore the original question and ask this as a new question? All the answers are completely irrelevant with your updates. – Allen Qin May 04 '17 at 22:13
  • @Charles B Guess it would make sense to post a new question with those edits. – Divakar May 04 '17 at 22:15
  • I have rolled back the edits that had changed the question to an entirely new form. Please post a new question. – Divakar May 04 '17 at 22:45

2 Answers2

3

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])
Allen Qin
  • 19,507
  • 8
  • 51
  • 67
1

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
Divakar
  • 218,885
  • 19
  • 262
  • 358