【问题标题】:How to Create a List of Pandas Series from a List of Dictionaries? [duplicate]从字典列表创建一个系列[重复]
【发布时间】:2021-06-25 02:27:20
【问题描述】:

我有以下列表:

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

我需要将每个“框架”键的值转换为 Pandas 系列,如下所示,以便稍后绘制:

aaa 50
bbb 12
ccc 23
ddd 72

阅读this 的文章后,我意识到 Pandas 系列的行为就像字典一样,索引可以是字符串。

到目前为止,我所做的只是能够迭代mylist,如下所示:

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

哪些输出:

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

有没有办法将此列表转换为 Pandas Series 对象?非常感谢任何帮助。

【问题讨论】:

    标签: python pandas dictionary series


    【解决方案1】:

    您只需要pd.Series(dictionary_variable)

    正如您展示的示例,我为您的问题提供了此代码,希望对您有所帮助:

    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)
        
    

    输出:

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

    但如果您想从每个帧制作熊猫系列,那么您只需要:

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

    输出:

    <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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2018-12-15
      相关资源
      最近更新 更多