2

I have two arrays of the same size:

import numpy as np
myArray = np.array([[5,3,2,1,2],
                    [2,5,3,3,3]])

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

I like to multiple all values in myArray by 5, but only if on the same index in myotherArray a value of 0 is. How do I do this? I tried this, but it doesn't do anything.

myArray[myotherArray == 0]*5 

My expected output is for myArray

([[25,3,2,5,10],
  [10,25,3,15,15]])

2 Answers 2

4

Multiply in place:

>>> myArray[myotherArray == 0] *= 5
>>> myArray
array([[25,  3,  2,  5, 10],
       [10, 25,  3, 15, 15]])
Sign up to request clarification or add additional context in comments.

Comments

3

Not sure if this is the most efficient way to do it, but:

>>> myArray * np.where(myotherArray == 0, 5, 1)
array([[25,  3,  2,  5, 10],
       [10, 25,  3, 15, 15]])

Another alternative:

>>> np.where(myotherArray == 0, 5*myArray, myArray)
array([[25,  3,  2,  5, 10],
       [10, 25,  3, 15, 15]])

Comments

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.