3

I have two Numpy arrays as follows:

>>> x
array([[0, 3, 3],
       [3, 3, 3],
       [0, 3, 3]])
>>> y
array([[0, 0, 0],
       [0, 2, 2],
       [0, 2, 2]])

Comparing x and y, I would like the comparison result to assign values based on the following conditions:

  1. If x and y values are nonzero, assign the lower value
  2. If x or y are zero, assign the non zero value
  3. If x and y are zero, assign 0

So referring to the above example, I would like the result to be:

>>> result
array([[0, 3, 3],
       [3, 2, 2],
       [0, 2, 2]])

Note: the array size is variable. I only took a 3 x 3 array as an example. x and y will be of the same size though.

How can I do this replacement/assignment operation using Numpy?

2 Answers 2

2

You can use built-in select for multi condition replacement:

np.select([(x!=0)&(y!=0), (x==0)!=(y==0), (x==0)&(y==0)],[np.minimum(x,y), x+y, 0])

output:

array([[0, 3, 3],
       [3, 2, 2],
       [0, 2, 2]])

although you can translate this multi condition into single condition and use adition for last two conditions with same output:

np.where((x!=0)&(y!=0), np.minimum(x,y), x+y)
Sign up to request clarification or add additional context in comments.

Comments

2

Here is a solution:

tmp = np.where(x == 0, y, x) # Rule 2 and 3
result = np.where((x != 0) & (y != 0), np.minimum(x, y), tmp) # Rule 1

Output in result:

array([[0, 3, 3],
       [3, 2, 2],
       [0, 2, 2]])

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.