如何计算numpy数组中元素的频率?

How to count frequency of a element in numpy array?

我有一个 3D numpy 数组,其中包含重复的元素。 counterTraj.shape (13530, 1, 1 例如 counterTraj 包含这样的元素:我只展示了几个元素:

         array([[[136.]],

       [[129.]],

       [[130.]],

       ...,

       [[103.]],

       [[102.]],

       [[101.]]])
```

我需要找到不同元素的频率:示例:136 计数 5(假设),101 计数 12(假设)。数组元素不固定,会随着输入数据的变化而变化。我尝试以下: from collections import Counter Counter(counterTraj) 生成以下错误:

> TypeError                                 Traceback (most recent 
    call last)
    <ipython-input-408-e3584b29b0bd> in <module>()
         11 counterTraj=np.vstack(counterTraj)
        12 counterTraj=counterTraj.reshape(len(counterTraj),1,1)
    ---> 13 Counter(counterTraj)
    /usr/lib/python3.6/collections/__init__.py in __init__(*args, 
   **kwds)
         533             raise TypeError('expected at most 1 arguments, 
      got %d' % len(args))
          534         super(Counter, self).__init__()
      --> 535         self.update(*args, **kwds)
         536 
       537     def __missing__(self, key):

     /usr/lib/python3.6/collections/__init__.py in update(*args, 
    **kwds)
         620                     super(Counter, self).update(iterable) # 
     fast path when counter is empty
         621             else:
      --> 622                 _count_elements(self, iterable)
       623         if kwds:
       624             self.update(kwds)

     TypeError: unhashable type: 'numpy.ndarray'

如何找到出现频率的元素并找到频率最高的元素?

使用 numpy.uniquereturn_counts=True 参数,这将 return 数组中每个元素的计数。

# sample array
In [89]: np.random.seed(23)
In [90]: arr = np.random.randint(0, 10, 20)

In [92]: a, cnts = np.unique(arr, return_counts=True)
In [94]: high_freq, high_freq_element = cnts.max(), a[cnts.argmax()]

In [95]: high_freq, high_freq_element
Out[95]: (4, 9)

要仅选择出现在特定频率阈值以上的元素,您可以使用:

In [96]: threshold = 2

# select elements which occur only more than 2 times
In [97]: a[cnts > threshold]
Out[97]: array([3, 5, 6, 9])