and0rsk - 11 months ago 85

Python Question

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`

`a`

`a < 0`

`[0,1]`

`[1,2]`

`a = -1, -4`

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`

`a`

`i, j`

`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 Source

Probably something like:

```
(a + b)*(a<0)
```

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