NumPy 数组中唯一值的频率计数

新手上路,请多包涵

如何有效地获取 NumPy 数组中每个唯一值的频率计数?

 >>> x = np.array([1,1,1,2,2,2,5,25,1,1])
>>> freq_count(x)
[(1, 5), (2, 3), (5, 1), (25, 1)]

原文由 Abe 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 727
2 个回答

看看 np.bincount

http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html

 import numpy as np
x = np.array([1,1,1,2,2,2,5,25,1,1])
y = np.bincount(x)
ii = np.nonzero(y)[0]

接着:

 zip(ii,y[ii])
# [(1, 5), (2, 3), (5, 1), (25, 1)]

或者:

 np.vstack((ii,y[ii])).T
# array([[ 1,  5],
         [ 2,  3],
         [ 5,  1],
         [25,  1]])

或者您想结合计数和唯一值。

原文由 JoshAdel 发布,翻译遵循 CC BY-SA 3.0 许可协议

numpy.uniquereturn_counts=True --- 一起使用(对于 NumPy 1.9+):

 import numpy as np

x = np.array([1,1,1,2,2,2,5,25,1,1])
unique, counts = np.unique(x, return_counts=True)

>>> print(np.asarray((unique, counts)).T)
 [[ 1  5]
  [ 2  3]
  [ 5  1]
  [25  1]]

scipy.stats.itemfreq 相比:

 In [4]: x = np.random.random_integers(0,100,1e6)

In [5]: %timeit unique, counts = np.unique(x, return_counts=True)
10 loops, best of 3: 31.5 ms per loop

In [6]: %timeit scipy.stats.itemfreq(x)
10 loops, best of 3: 170 ms per loop

原文由 jme 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题