count the frequency that a value occurs in a dataframe column

后端 未结 13 1883
耶瑟儿~
耶瑟儿~ 2020-11-22 03:29

I have a dataset

|category|
cat a
cat b
cat a

I\'d like to be able to return something like (showing unique values and frequency)



        
13条回答
  •  花落未央
    2020-11-22 03:58

    In 0.18.1 groupby together with count does not give the frequency of unique values:

    >>> df
       a
    0  a
    1  b
    2  s
    3  s
    4  b
    5  a
    6  b
    
    >>> df.groupby('a').count()
    Empty DataFrame
    Columns: []
    Index: [a, b, s]
    

    However, the unique values and their frequencies are easily determined using size:

    >>> df.groupby('a').size()
    a
    a    2
    b    3
    s    2
    

    With df.a.value_counts() sorted values (in descending order, i.e. largest value first) are returned by default.

提交回复
热议问题