将pandas.Series.value_counts返回的系列转换为字典 [英] convert series returned by pandas.Series.value_counts to a dictionary
本文介绍了将pandas.Series.value_counts返回的系列转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用pandas.Series.value_counts来获取数据帧中值的频率,因此我遍历每一列并获取values_count,这给了我一个系列:
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:
我正在努力将此结果系列转换为dict:
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
我需要的是字典:
{'high':3909,'average':3688,'less':'182,'veryless':62}
{'high': 3909 , 'average': 3688, 'less': '182 , 'veryless' : 62}
推荐答案
如果要将Series
转换为dict
,可以调用dict
或.to_dict()
:
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}
这篇关于将pandas.Series.value_counts返回的系列转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文