gpt4 book ai didi

python - 将 JSON 对象的一部分存储在 pandas df 中

转载 作者:行者123 更新时间:2023-11-30 21:52:30 25 4
gpt4 key购买 nike

我正在尝试将以下内容存储到 pandas 数据框中:

{    
"page": 1,
"results": [
{
"poster_path": null,
"adult": false,
"overview": "Go behind the scenes during One Directions sell out \"Take Me Home\" tour and experience life on the road.",
"release_date": "2013-08-30",
"genre_ids": [
99,
10402
],
"id": 164558,
"original_title": "One Direction: This Is Us",
"original_language": "en",
"title": "One Direction: This Is Us",
"backdrop_path": null,
"popularity": 1.166982,
"vote_count": 55,
"video": false,
"vote_average": 8.45
},
{
"poster_path": null,
"adult": false,
"overview": "",
"release_date": "1954-06-22",
"genre_ids": [
80,
18
],
"id": 654,
"original_title": "On the Waterfront",
"original_language": "en",
"title": "On the Waterfront",
"backdrop_path": null,
"popularity": 1.07031,
"vote_count": 51,
"video": false,
"vote_average": 8.19
}
etc....
etc.....
],
"total_results": 61,
"total_pages": 4
}

将每个结果的所有属性存储在 pandas 数据框中的最简单方法是什么?

我将 json 对象存储在 dict 变量中。我真的需要迭代存储在 dict 变量中的结果 block 并为每个 pandas 列定义每个字段吗?

这是我试图避免的:

columns = ['filmid', 'title'....... ]

# create dataframe
df = pandas.DataFrame(columns=columns)


for film in films:

df.loc[len(df)]=[film['id'],title['title']........................]

最佳答案

您可以使用json_normalize函数。这是一个例子:

import json
from pandas.io.json import json_normalize

#Load data
with open('yourfile.json') as file:
data = json.load(file)

flat_json_df = json_normalize(data['results'])

对我来说,当使用上面的数据时,它会产生以下数据帧:

adult   backdrop_path   genre_ids   id  original_language   original_title  overview    popularity  poster_path release_date    title   video   vote_average    vote_count
0 False None [99, 10402] 164558 en One Direction: This Is Us Go behind the scenes during One Directions sel... 1.166982 None 2013-08-30 One Direction: This Is Us False 8.45 55
1 False None [80, 18] 654 en On the Waterfront 1.070310 None 1954-06-22 On the Waterfront False 8.19 51

关于python - 将 JSON 对象的一部分存储在 pandas df 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59886050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com