2 个回答
In [1]: import numpy as np

In [2]: from collections import Counter

In [3]: a = np.array([[1,2],[3,4]])

In [4]: Counter(a.flatten())
Out[4]: Counter({1: 1, 2: 1, 3: 1, 4: 1})

In [5]: b = np.array([[1,1],[3,4]])
In [6]: Counter(b.flatten())
Out[6]: Counter({1:2, 3: 1, 4: 1})

bincount

python3

>>> import numpy as np
>>> a=np.random.randint(1,10,15).reshape(3,5)
>>> a
array([[4, 4, 1, 8, 4],
       [7, 5, 8, 8, 1],
       [5, 5, 1, 2, 7]])
>>> c=np.bincount(a.flat)
>>> c
array([0, 3, 1, 0, 3, 3, 0, 2, 3], dtype=int32)
>>> d=np.vstack((np.where(c>0), c[c>0]))
>>> d
array([[1, 2, 4, 5, 7, 8], # 值
       [3, 1, 3, 3, 2, 3]], dtype=int32) # 个数
>>> 

unique

>>> a=np.random.randint(1,10,15).reshape(3,5)/10
>>> a
array([[ 0.6,  0.8,  0.3,  0.5,  0.7],
       [ 0.7,  0.6,  0.7,  0.4,  0.4],
       [ 0.1,  0.8,  0.4,  0.5,  0.5]])
>>> 值,个数 = np.unique(a, return_counts=True)
>>> np.vstack((值, 个数))
array([[ 0.1,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8],
       [ 1. ,  1. ,  3. ,  3. ,  2. ,  3. ,  2. ]])
>>> 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题