Python – 将嵌套字典列表转换为Pandas数据帧
很多时候,Python会从不同的源接收数据,这些数据可以是不同的格式,如csv、JSON等,可以转换为Python列表或字典等。但是,为了使用像pandas这样的包进行计算或分析,我们需要将这些数据转换为数据帧。在本文中,我们将看到如何将一个给定的Python列表转换为Pandas数据帧,其元素是嵌套字典。
首先,我们取出嵌套字典列表的数据行。 然后,我们创建另一个for循环,将行附加到最初创建的空列表中。 最后,我们应用Pandas库中的DataFrames函数来创建数据帧。
示例
import pandas as pd
# 给定嵌套字典
list = [
{
"Fruit": [{"Price": 15.2, "Quality": "A"},
{"Price": 19, "Quality": "B"},
{"Price": 17.8, "Quality": "C"},
],
"Name": "Orange"
},
{
"Fruit": [{"Price": 23.2, "Quality": "A"},
{"Price": 28, "Quality": "B"}
],
"Name": "Grapes"
}
]
rows = []
# 获取行
for data in list:
data_row = data['Fruit']
n = data['Name']
for row in data_row:
row['Name'] = n
rows.append(row)
# 转换成数据帧
df = pd.DataFrame(rows)
print(df)
运行上述代码会给出以下结果 −
输出
Price Quality Name
0 15.2 A Orange
1 19.0 B Orange
2 17.8 C Orange
3 23.2 A Grapes
4 28.0 B Grapes
应用透视表
我们还可以应用pivot_table函数来重新组织数据。
示例
import pandas as pd
# 初始化嵌套字典列表
list = [
{
"Fruit": [{"Price": 15.2, "Quality": "A"},
{"Price": 19, "Quality": "B"},
{"Price": 17.8, "Quality": "C"},
],
"Name": "Orange"
},
{
"Fruit": [{"Price": 23.2, "Quality": "A"},
{"Price": 28, "Quality": "B"}
],
"Name": "Grapes"
}
]
#print(list)
rows = []
# 添加行
for data in list:
data_row = data['Fruit']
n = data['Name']
for row in data_row:
row['Name'] = n
rows.append(row)
# 使用数据帧
df = pd.DataFrame(rows)
df = df.pivot_table(index='Name', columns=['Quality'],
values=['Price']).reset_index()
print(df)
运行上述代码会给出以下结果 −
输出
Name Price
Quality A B C
0 Grapes 23.2 28.0 NaN
1 Orange 15.2 19.0 17.8
极客教程