Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
919 views
in Technique[技术] by (71.8m points)

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

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}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...