Efficient way to count unique elements in array in numpy/scipy in Python
numpy, python, scipy
Solution
If sticking with Python 2.7 (or 3.1) is not an issue and any of these two Python versions is available to you, perhaps the new collections.Counter might be something for you if you stick to hashable elements like tuples:
>>> from collections import Counter
>>> c = Counter([(0,0,1), (1,1,1), (1,1,1), (1,0,1)])
>>> c
Counter({(1, 1, 1): 2, (0, 0, 1): 1, (1, 0, 1): 1})
I haven't done any performance testing on these two approaches, though.
Problem
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.