在Python中以numpy/scipy计数数组中唯一元素的有效方法 [英] Efficient way to count unique elements in array in numpy/scipy in Python

查看:203
本文介绍了在Python中以numpy/scipy计数数组中唯一元素的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个scipy数组,例如

I have a scipy array, e.g.

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

我想计算数组中每个唯一元素的出现次数.例如,对于上面的数组a,我想知道有1个出现的[0,0,1],2个出现的[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].

我想到的一种方法是:

from collections import defaultdict
d = defaultdict(int)

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

有没有更好/更有效的方法?

is there a better/more efficient way?

谢谢.

推荐答案

如果坚持使用Python 2.7(或3.1)不是问题,并且您可以使用这两个Python版本中的任何一个,也许是新的 collections.Counter 可能对您有用:

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.

这篇关于在Python中以numpy/scipy计数数组中唯一元素的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆