0

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.

2
  • what does the error say? Commented Sep 16, 2021 at 15:40
  • TypeError: '>' not supported between instances of 'builtin_function_or_method' and 'int' Commented Sep 16, 2021 at 15:42

2 Answers 2

3
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.