ashnair1
ashnair1

Reputation: 365

Numpy arrays: multi conditional assignment

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?

Upvotes: 3

Views: 1188

Answers (2)

Ehsan
Ehsan

Reputation: 12407

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)

Upvotes: 2

Jérôme Richard
Jérôme Richard

Reputation: 50688

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]])

Upvotes: 2

Related Questions