1

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?

Gulzar
  • 17,272
  • 18
  • 86
  • 144

1 Answers1

1
# 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 an array
search = np.array([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]

Spencer Stream
  • 617
  • 2
  • 5
  • 21