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

问题描述 投票:1回答:1

我有一个3 D 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'

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

python numpy counter counting numpy-ndarray
1个回答
2
投票

numpy.uniquereturn_counts=True参数一起使用,该参数将返回数组中每个元素的计数。

# 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])
© www.soinside.com 2019 - 2024. All rights reserved.