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

后端 未结 2 2046
孤城傲影
孤城傲影 2020-12-10 11:15

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:

相关标签:
2条回答
  • 2020-12-10 11:44

    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))
    
    0 讨论(0)
  • 2020-12-10 12:00

    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}
    
    0 讨论(0)
提交回复
热议问题