equivalent of value_counts of Pandas in NumPy

Viewed 681

Pandas's value_counts function outputs the counts of each element in a Pandas series.

If I need to count each unique elements of a list, I need to make it into a Pandas series and then call the value_counts function.

Is there a function that does the same thing in NumPy?

1 Answers

np.unique returns the unique elements of an array, but it also has an optional return_counts parameter which causes np.unique to return both the unique elements and for each unique element, the number of times it appeared in the original array, like Pandas's value_counts:

>>> a = np.array([1,2,3,4,5,4,3,2,1])
>>> unique, counts = np.unique(a, return_counts=True)
>>> unique
array([1, 2, 3, 4, 5])

>>> counts
array([2, 2, 2, 2, 1])
Related