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

后端 未结 4 874
傲寒
傲寒 2021-02-02 15:16

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 ele

4条回答
  •  灰色年华
    2021-02-02 15:33

    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.

提交回复
热议问题