3

Do you know how to sum up all negative elements in each column of a NumPy array. For example

>>> d array([[ 1, 2, 3], [-1, -1, 9], [ 7, -6, 4]]) 

I need to get [-1,-7,0]. Is there a function to do so?

1

1 Answer 1

13

Few approaches could be suggested, as listed below -

((d<0)*d).sum(0) np.where(d<0,d,0).sum(0) np.einsum('ij,ij->j',d<0,d) ((d - np.abs(d)).sum(0))/2 

Sample step-by-step run with explanation for all those approaches -

1) Input array :

In [3]: d Out[3]: array([[ 1, 2, 3], [-1, -1, 9], [ 7, -6, 4]]) 

2) Mask of negative elements :

In [4]: d<0 Out[4]: array([[False, False, False], [ True, True, False], [False, True, False]], dtype=bool) 

3) Get masked negative elements off input array using element-wise multiplication :

In [5]: (d<0)*d Out[5]: array([[ 0, 0, 0], [-1, -1, 0], [ 0, -6, 0]]) 

4) Finally, sum along axis=0 to sum along each column :

In [6]: ((d<0)*d).sum(axis=0) # Or simply ((d<0)*d).sum(0) Out[6]: array([-1, -7, 0]) 

Approach#2 : 3) Get step (3) results alternatively with np.where :

In [7]: np.where(d<0,d,0) Out[7]: array([[ 0, 0, 0], [-1, -1, 0], [ 0, -6, 0]]) 

Approach#3 : 3,4) Perform elementwise multiplication between mask and array and get the summation, all in one step using np.einsum -

In [8]: np.einsum('ij,ij->j',d<0,d) Out[8]: array([-1, -7, 0]) 

Approach#4 : Get the absolute values of input array and subtract from the array itself, giving us double of the negative elements and the positive values being canceled out :

In [9]: d - np.abs(d) Out[9]: array([[ 0, 0, 0], [ -2, -2, 0], [ 0, -12, 0]]) 

Sum along each column and divide by 2 for desired output :

In [10]: (d - np.abs(d)).sum(0) Out[10]: array([ -2, -14, 0]) In [11]: ((d - np.abs(d)).sum(0))/2 Out[11]: array([-1, -7, 0]) 
Sign up to request clarification or add additional context in comments.

4 Comments

The last approach has two downsides: It can lead to overflow where the others would still work and it would give a float array in python3. Maybe better ((d - np.abs(d)) // 2).sum(0) (that doesn't take care of all overflow issues but at least of some).
thanks a lot! i just want to make sure i understood - for the first option -((d<0)*d).sum(0)- the zero inside the sum is for the axis (cols) and the *d (the second d) is because that inside the Brackets we got true/false matrix (e.g. zeros and ones) - so after that, in order to get the sum - we have to multiply by d?
@noamishal Check out the just added step by step run with explanation if that helps out.
@noamishal Did the posted solution and the comments clarify your doubts?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.