Sendi_t
Sendi_t

Reputation: 647

Summing positive and negative elements from two NumPy arrays

>>> x1
array([[ 0.,  -1.,   2.],
       [ 3.,  -4.,  2.],
       [ -2.,  1.,  -8.]])

>>> x3
array([[ 0.,  -5.,  2.],
       [ 3.,  0.,  -3.],
       [ 3.,  2.,  8.]])

I need two matricies to be output: S and T, such that X is the sum of all positive values in X and Y, and T is the sum of all negative values in X and Y.

For example:

      S = array([   [ 0.,  0.,  4.],
                    [ 6.,  0.,  2.],
                    [ 3.,  3.,  8.]])

      T = array([   [ 0.,  -6.,  0.],
                    [ 0.,  -4.,  -3.],
                    [ -2.,  0.,  -8.]])  

I am using Python 2.6.7.

Upvotes: 1

Views: 2673

Answers (2)

YXD
YXD

Reputation: 32521

As well as clip you can do this by multiplying by boolean arrays:

>>> x1 * (x1 > 0) + x3 * (x3 > 0)
array([[ 0., -0.,  4.],
       [ 6.,  0.,  2.],
       [ 3.,  3.,  8.]])
>>> x1 * (x1 <= 0) + x3 * (x3 <= 0)
array([[ 0., -6.,  0.],
       [ 0., -4., -3.],
       [-2.,  0., -8.]])
>>>

Upvotes: 1

Zero
Zero

Reputation: 76947

You can use np.clip() to selectively add

In [140]: x1.clip(min=0) + x3.clip(min=0)
Out[140]:
array([[ 0.,  0.,  4.],
       [ 6.,  0.,  2.],
       [ 3.,  3.,  8.]])

In [141]: x1.clip(max=0) + x3.clip(max=0)
Out[141]:
array([[ 0., -6.,  0.],
       [ 0., -4., -3.],
       [-2.,  0., -8.]])

Upvotes: 3

Related Questions