Numpy Array Conditional Operation Mask?

Tags: , ,



Suppose you have an array:

a = [ 0,1,0] [-1,2,1] [3,-4,2]

And lets say you add 20 to everything

b = [ 20, 21, 20] [ 19, 22, 21] [ 23, 16, 22]

Now lets say I want to add the resulting b to the original array a but only in cases where a < 0 i.e at the index [0,1] and [1,2] where a = -1, -4 respectively getting the value 0 otherwise. Ultimately leading to a matrix as such:

c = [ 0, 0, 0] [ 18, 0, 0] [ 0, 12, 0] 18 = 19 (from b) + -1 (from a) 12 = 16 (from b) + -4 (from a)

And assume that I want to be able to extend this to any operation (not just add 20), so that you can’t just filter all values < 20 from matrix c. So I want to use matrix a as a mask toward matrix c, zeroing the i, j where a[i,j] < 0.

I’m having a tough time finding a concise example of how to do this in numpy with python. I was hoping you may be able to direct me to the correct implementation of such a method.

What I am struggling to get is this into a mask and only performing operations on the retained values, finally resulting in c.

Thanks for the help in advance.

Answer

Probably something like:

(a + b)*(a<0)

should work unless you have very strong requirements concerning the number of intermediate arrays.



Source: stackoverflow