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
  • 23,452
  • 27
  • 113
  • 201

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 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]

Gulzar
  • 23,452
  • 27
  • 113
  • 201
Spencer Stream
  • 616
  • 2
  • 6
  • 22