[Django]-Count frequency of values in pandas DataFrame column

153๐Ÿ‘

โœ…

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}
๐Ÿ‘คjezrael

14๐Ÿ‘

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}
๐Ÿ‘คColonel Beauvel

9๐Ÿ‘

You can try this way.

df.stack().value_counts().to_dict()
๐Ÿ‘คsu79eu7k

2๐Ÿ‘

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)}
๐Ÿ‘คChuck

1๐Ÿ‘

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)
๐Ÿ‘คdjoguns

Leave a comment