Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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} 
like image 267
swati saoji Avatar asked Apr 02 '15 00:04

swati saoji


People also ask

How do you turn a series into a dictionary?

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.

What does Value_counts return in pandas?

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.

How can I convert panda to dictionary?

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 do you turn a series object into a list?

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.


2 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} 
like image 87
DSM Avatar answered Oct 08 '22 23:10

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)) 
like image 23
Martin Thoma Avatar answered Oct 08 '22 22:10

Martin Thoma