convert series returned by pandas.Series.value_counts to a dictionary

Question:

I am trying to use pandas.Series.value_counts to get the frequency of values in a dataframe, so I go through each column and get values_count , which gives me a series:

I am struggling to convert this resultant series to a dict:

 groupedData = newData.groupby('class')
for k, group in groupedData:
    dictClass[k] = {}
    for eachlabel in dataLabels:
        myobj = group[eachlabel].value_counts()
        for eachone in myobj:
            print type(myobj)
            print myobj

The snippet

what I need is a dict :

{'high': 3909 , 'average': 3688, 'less': '182 , 'veryless' : 62}
Asked By: swati saoji

||

Answers:

If you want to convert a Series to a dict, you could call dict or .to_dict():

>>> s
high        3909
average     3688
less         182
veryless      62
dtype: int64
>>> type(s)
<class 'pandas.core.series.Series'>
>>> dict(s)
{'high': 3909, 'average': 3688, 'veryless': 62, 'less': 182}
>>> s.to_dict()
{'high': 3909, 'average': 3688, 'veryless': 62, 'less': 182}
Answered By: DSM

Extract keys and values for the dictionary from your_column and then zip it together.

values = df['your_column'].value_counts(dropna=False).keys().tolist()
counts = df['your_column'].value_counts(dropna=False).tolist()
value_dict = dict(zip(values, counts))
Answered By: Martin Thoma
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.