William
William

Reputation: 81

Count Instances in One Array Based on Another Array

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.

Upvotes: 1

Views: 620

Answers (2)

Jaime
Jaime

Reputation: 67487

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

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

Upvotes: 0

jpp
jpp

Reputation: 164793

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.

Upvotes: 1

Related Questions