1

I am wondering if there is an efficient way to perform the following. I have two (numpy) arrays, and I would like to count the number of instances of a value occurring in one based on the criteria of another another array. For example:

a = np.array([1,-1,1,1,-1,-1])
b = np.array([.75,.35,.7,.8,.2,.6])

I would like to calculate c as the number of 1's in a that occur when b > .5, so in this case `c = 3'. My current solution is ugly and would appreciate any suggestions.

2 Answers 2

1

You can use numpy.sum for this:

a = np.array([1,-1,1,1,-1,-1])
b = np.array([.75,.35,.7,.8,.2,.6])

np.sum((a == 1) & (b > .5))  # 3

This works because bool is a subclass of int.

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

Comments

0

If it's only one condition you are after, try:

np.count_nonzero((a == 1) & (b > .5))

3 Comments

Or if the desired answer is 3 then np.count_nonzero?
np.count_nonzero((a == 1) & (b > .5)) is what I was looking for. Thanks @Da
Indeed! Thanks for the correction, have updated my answer.

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.