我有一个 scipy 数组,例如
a = array([[0, 0, 1], [1, 1, 1], [1, 1, 1], [1, 0, 1]])
我想计算数组中每个唯一元素出现的次数。例如,对于上面的数组 a,我想找出 [0, 0, 1] 出现 1 次,[1, 1, 1] 出现 2 次,[1, 0, 1] 出现 1 次。
我想到的一种方法是:
from collections import defaultdict
d = defaultdict(int)
for elt in a:
d[elt] += 1
有没有更好/更有效的方法?
谢谢。
最佳答案
如果坚持使用 Python 2.7(或 3.1)不是问题,并且您可以使用这两个 Python 版本中的任何一个,也许是新的 collections.Counter如果您坚持使用元组等可散列元素,可能适合您:
>>> 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})
不过,我还没有对这两种方法进行任何性能测试。
关于python - 在 Python 的 numpy/scipy 中计算数组中唯一元素的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4037262/