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?
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?
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]) ((d - np.abs(d)) // 2).sum(0) (that doesn't take care of all overflow issues but at least of some).