Reputation: 91
I have numpy array:
wk = np.array([1, 0, 3, -4])
how to apply a formula based on certain condition, like how to sum all positive value in wk
. I've tried
if wk.all > 0:
np.sum(wk)
But it threw an error.
Upvotes: 0
Views: 270
Reputation: 125
for the positive values you can use:
import numpy as np
wk = np.array([1, 0, 3, -4])
sum = wk[wk>0].sum() # returns array of elements which are positive and then adds them
similarly you can put conditions inside wk[condition_here]
Upvotes: 1
Reputation: 165
np.sum(wk[wk > 0])
is what you are looking for. wk > 0
creates a boolean array of the same size as wk
that is true everywhere where wk > 0
. wk[wk > 0]
then evaluates to an array that only contains those elements of wk
where the former array is true and finally np.sum
sums up those values.
Upvotes: 3