Search code examples
pythonpandasdictionaryseries

How to Create a List of Pandas Series from a List of Dictionaries?


I have the following list:

mylist = [
   { 'frame': { 'aaa': 50 } },
   { 'frame': { 'bbb': 12 } },
   { 'frame': { 'ccc': 23 } },
   { 'frame': { 'ddd': 72 } }
]

I need to convert the values of each of those 'frame' keys to a Pandas Series such as the following so that I can plot later on:

aaa 50
bbb 12
ccc 23
ddd 72

After reading this article, I realized that Pandas Series behave like dictionaries where indices can be strings.

So far, what I have only done is be able to iterate mylist as follows:

for element in mylist :
    print(type(element['frame']), element['frame'])

Which outputs:

<class 'dict'> {'aaa': 50}
<class 'dict'> {'bbb': 12}
<class 'dict'> {'ccc': 23}
<class 'dict'> {'ddd': 72}

Is there any way to convert this list to a Pandas Series object? Any help is highly appreciated.


Solution

  • All you need is pd.Series(dictionary_variable)

    As the example you shown, I provide this code for your problem, hope to be helpful:

    import pandas as pd
    
    mylist = [
       { 'frame': { 'aaa': 50 } },
       { 'frame': { 'bbb': 12 } },
       { 'frame': { 'ccc': 23 } },
       { 'frame': { 'ddd': 72 } }
    ]
    return_dict = {}
    for dictionary in mylist:
        inner_dict = dictionary["frame"]
        key = list(inner_dict.keys())[0]
        value = inner_dict[key]
        return_dict[key] = value
    
    series = pd.Series(return_dict)
    print(type(series))
    print(series)
        
    

    Output:

    <class 'pandas.core.series.Series'>
    aaa    50
    bbb    12
    ccc    23
    ddd    72
    dtype: int64
    

    But if you want to make pandas series from each of the frames so you just need:

    import pandas as pd
    mylist = [
       { 'frame': { 'aaa': 50 } },
       { 'frame': { 'bbb': 12 } },
       { 'frame': { 'ccc': 23 } },
       { 'frame': { 'ddd': 72 } }
    ]
    
    return_dict = {}
    for dictionary in mylist:
        inner_dict = dictionary["frame"]
        series = pd.Series(inner_dict)
        print(type(series), series, sep=" ")
    

    Output:

    <class 'pandas.core.series.Series'> aaa    50
    dtype: int64
    <class 'pandas.core.series.Series'> bbb    12
    dtype: int64
    <class 'pandas.core.series.Series'> ccc    23
    dtype: int64
    <class 'pandas.core.series.Series'> ddd    72
    dtype: int64