Count frequency of values ​​in pandas DataFrame column

I want to count the number of times each value appears in a data frame.

Here is my dataframe - df:

    status
1     N
2     N
3     C
4     N
5     S
6     N
7     N
8     S
9     N
10    N
11    N
12    S
13    N
14    C
15    N
16    N
17    N
18    N
19    S
20    N

I want a dictionary of words:

ex. counts = {N: 14, C:2, S:4}

I tried df['status']['N'], but it gives keyErroras well df['status'].value_counts, but is not used.

+12
source share
5 answers

You can use value_countsand 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}
+37
source

Alternative single liner using underdog Counter:

In [3]: from collections import Counter

In [4]: dict(Counter(df.status))
Out[4]: {'C': 2, 'N': 14, 'S': 4}
+5
source

.

df.stack().value_counts().to_dict()
+4

df ?

:

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

dict:

c = {i: a.count(i) for i in set(a)}
+1
source

See my answer in this thread for Pandas DataFrame output,

count the frequency of occurrence of a value in a data column

To display the dictionary, you can change it 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
source

All Articles