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
what I need is a dict :
{'high': 3909 , 'average': 3688, 'less': '182 , 'veryless' : 62}
to_dict() function is used to convert the given Series object to {label -> value} dict or dict-like object. Parameter : into : The collections. Mapping subclass to use as the return object.
Return a Series containing counts of unique values. The resulting object will be in descending order so that the first element is the most frequently-occurring element.
To convert pandas DataFrame to Dictionary object, use to_dict() method, this takes orient as dict by default which returns the DataFrame in format {column -> {index -> value}} . When no orient is specified, to_dict() returns in this format.
How to use the tolist() method to convert pandas series to list. To convert a pandas Series to a list, simply call the tolist() method on the series which you wish to convert.
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}
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With