Count frequency of values in pandas DataFrame column

后端 未结 5 772
死守一世寂寞
死守一世寂寞 2020-11-29 05:47

I want to count number of times each values is appearing in dataframe.

Here is my dataframe - df:

    status
1     N
2     N
3     C
4           


        
相关标签:
5条回答
  • 2020-11-29 06:10

    See my response in this thread for a Pandas DataFrame output,

    count the frequency that a value occurs in a dataframe column

    For dictionary output, you can modify as follows:

    def column_list_dict(x):
        column_list_df = []
        for col_name in x.columns:        
            y = col_name, len(x[col_name].unique())
            column_list_df.append(y)
        return dict(column_list_df)
    
    0 讨论(0)
  • You can try this way.

    df.stack().value_counts().to_dict()
    
    0 讨论(0)
  • 2020-11-29 06:26

    You can use value_counts and to_dict:

    print df['status'].value_counts()
    N    14
    S     4
    C     2
    Name: status, dtype: int64
    
    counts = df['status'].value_counts().to_dict()
    print counts
    {'S': 4, 'C': 2, 'N': 14}
    
    0 讨论(0)
  • 2020-11-29 06:27

    An alternative one liner using underdog Counter:

    In [3]: from collections import Counter
    
    In [4]: dict(Counter(df.status))
    Out[4]: {'C': 2, 'N': 14, 'S': 4}
    
    0 讨论(0)
  • 2020-11-29 06:32

    Can you convert df into a list?

    If so:

    a = ['a', 'a', 'a', 'b', 'b', 'c']
    c = dict()
    for i in set(a):
        c[i] = a.count(i)
    

    Using a dict comprehension:

    c = {i: a.count(i) for i in set(a)}
    
    0 讨论(0)
提交回复
热议问题