1
 y = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])

 indices_of_y = np.array([12, 0, 6, 3, 4, 9, 11, 2])

            z = np.array([1 , 1, 0, 1, 1, 1, 0,  0])

            x = np.array([1,  1, 1, 0, 1, 0, 0,  1])

 n = 3

I want to compare arrays z and x element wise and I want to add n to only those elements of y where the elements of z and x differ. In the case that the elements of z and x are different, I add n to the element of y in the index position indicated in indices_of_y.

The answer should be:

y = [1, 2, 6, 7, 5, 6, 10, 8, 9, 13, 11, 12, 13, 14, 15, 16]  
Charles B
  • 95
  • 3
  • 14

1 Answers1

1

To test for elementwise equality you do

z != x               #  array([False, False,  True,  True, False,  True, False,  True], dtype=bool)

the result you can use to extract the indices you want using

indices_of_y[z != x] #  array([6, 3, 9, 2])

which in turn you use as index of y. But since y is 2D and your index is 1D, we need to temporarily flatten y first using

y.ravel()            #  array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16])

Since y.ravel() returns a view instead of a copy we can manipulate all elements directly and will see the change in y, too. So you combine the three to

y.ravel()[indices_of_y[z != x]] += n

and see the result

print(y)
# array([[ 1,  2,  6,  7],
#        [ 5,  6, 10,  8],
#        [ 9, 13, 11, 12],
#        [13, 14, 15, 16]])
Nils Werner
  • 34,832
  • 7
  • 76
  • 98