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]  

1 Answer 1

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

Simply perfect :) what I wanted. Thank you !! @Nils Werner

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.