How to count the frequency of the elements in an unordered list?

后端 未结 30 2903
时光说笑
时光说笑 2020-11-22 02:37

I need to find the frequency of elements in an unordered list

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]

output->

b =         


        
30条回答
  •  醉酒成梦
    2020-11-22 03:08

    You can do this:

    import numpy as np
    a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
    np.unique(a, return_counts=True)
    

    Output:

    (array([1, 2, 3, 4, 5]), array([4, 4, 2, 1, 2], dtype=int64))
    

    The first array is values, and the second array is the number of elements with these values.

    So If you want to get just array with the numbers you should use this:

    np.unique(a, return_counts=True)[1]
    

提交回复
热议问题