How to count occurances of multiple items in numpy?

Question:

Assume the folowing numpy array:

[1,2,3,1,2,3,1,2,3,1,2,2]

I want to count([1,2]) to count all occurrences of 1 and 2, in a single run, yielding something like

[4, 5]

corresponding to a [1, 2] input.

Is it supported in numpy?

Asked By: Gulzar

||

Answers:

# Setting your input to an array
array = np.array([1,2,3,1,2,3,1,2,3,1,2,2])

# Find the unique elements and get their counts
unique, counts = np.unique(array, return_counts=True)

# Setting the numbers to get counts for as a set
search = {1, 2}

# Gets the counts for the elements in search
search_counts = [counts[i] for i, x in enumerate(unique) if x in search]

This will output [4, 5]

Answered By: Spencer Stream
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.