dzdws
dzdws

Reputation: 91

Applying formula based on condition in numpy array

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

Answers (2)

Tanish Surana
Tanish Surana

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

Homan
Homan

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

Related Questions