如何从字典列表中创建 Pandas 系列的列表?

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

我有以下列表:

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

我需要将每个 'frame' 键的值转换为 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 系列对象?非常感谢任何帮助。

你只需要 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

但是如果你想从 每个 帧制作 pandas 系列,那么你只需要:

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