I'm looking for an extension to this question Efficiently counting number of unique elements - NumPy / Python that can also return the count of each unique element (i.e. how many times it occurs in the array).
import numpy as np
max_a = 20_000
a = np.random.randint(max_a, size=10_000).astype(np.int32)
# Using np.unique
u,counts = np.unique(a,return_counts=True)
# Faster alternative suggested in the post above
q = np.zeros(max_a, dtype=int)
q[a] = 1
v = np.nonzero(q)[0]
I can verify that u
and v
are the same, and the faster method using q
is definitely faster. However, I also want the counts
that are returned by the np.unique()
call. Is there a way to modify the example here to obtain those?
NB the elements of a will always be of type np.int32
so they can be used for indexing.