Is there any function to find the frequency of each element present in a list or Numpy array? I can write a code small code for this, but I need some function if there exists any.

+2 votes

Best answer

You can use either **numpy****.unique()** or** ****scipy****.stats.itemfreq() **to find the frequency of list items. Have a look at the following examples.

**Approach 1**

>>> b

array([2, 1, 2, 0, 2, 1, 2, 1, 2, 1, 2], dtype=int64)

>>> import scipy

>>> scipy.stats.itemfreq(b)

array([[0, 1],

[1, 4],

[2, 6]], dtype=int64)

**Approach 2**

>>> val,count=np.unique(b,return_counts=True)

>>> print np.asarray((val,count)).T

[[0 1]

[1 4]

[2 6]]