Himal Acharya
Himal Acharya

Reputation: 1006

How to count frequency of a element in numpy array?

I have a 3 D numpy array which contains elements with repetition. counterTraj.shape (13530, 1, 1 For example counterTraj contains such elements: I have shown few elements only:

         array([[[136.]],

       [[129.]],

       [[130.]],

       ...,

       [[103.]],

       [[102.]],

       [[101.]]])
```

I need to find frequency of different element: Example: 136 count 5 (say), 101 count 12 (say). The array elements are not fixed and changes with input data. I try following: from collections import Counter Counter(counterTraj) Following error generates:

> 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'

How to find occurence of element with frequency and find highest frequency element?

Upvotes: 2

Views: 7210

Answers (1)

kmario23
kmario23

Reputation: 61305

Use numpy.unique with return_counts=True parameter, which will return the count of each of the elements in the array.

# 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)

For selecting only the elements which appear above a certain frequency threshold, you can use:

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])

Upvotes: 3

Related Questions