将 pandas.Series.value_counts 返回的系列转换为字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29403192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:09:01  来源:igfitidea点击:

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

pythonpandas

提问by swati saoji

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:

我正在尝试使用 pandas.Series.value_counts 来获取数据框中值的频率,因此我遍历每一列并获取 values_count ,这给了我一个系列:

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}

{'high':3909,'average':3688,'less':'182,'veryless':62}

回答by DSM

If you want to convert a Seriesto a dict, you could call dictor .to_dict():

如果要将 a 转换Series为 a dict,可以调用dict.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}

回答by Martin Thoma

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))