Efficient way to count unique elements in array in numpy/scipy in Python

Viewed 13871

I have a scipy array, e.g.

a = array([[0, 0, 1], [1, 1, 1], [1, 1, 1], [1, 0, 1]])

I want to count the number of occurrences of each unique element in the array. For example, for the above array a, I want to get out that there is 1 occurrence of [0, 0, 1], 2 occurrences of [1, 1, 1] and 1 occurrence of [1, 0, 1].

One way I thought of doing it is:

from collections import defaultdict
d = defaultdict(int)

for elt in a:
  d[elt] += 1

is there a better/more efficient way?

thanks.

4 Answers
Related