gpt4 book ai didi

python - 将 JSON 文件转换为 Pandas 数据帧

转载 作者:行者123 更新时间:2023-12-03 03:01:50 24 4
gpt4 key购买 nike

我想将 JSON 转换为 Pandas 数据帧。

我的 JSON 如下所示:像:

{ 
"country1":{
"AdUnit1":{
"floor_price1":{
"feature1":1111,
"feature2":1112
},
"floor_price2":{
"feature1":1121
}
},
"AdUnit2":{
"floor_price1":{
"feature1":1211
},
"floor_price2":{
"feature1":1221
}
}
},
"country2":{
"AdUnit1":{
"floor_price1":{
"feature1":2111,
"feature2":2112
}
}
}
}

我使用以下代码从 GCP 读取文件:

project = Context.default().project_id
sample_bucket_name = 'my_bucket'
sample_bucket_path = 'gs://' + sample_bucket_name
print('Object: ' + sample_bucket_path + '/json_output.json')

sample_bucket = storage.Bucket(sample_bucket_name)
sample_bucket.create()
sample_bucket.exists()

sample_object = sample_bucket.object('json_output.json')
list(sample_bucket.objects())
json = sample_object.read_stream()

我的目标是获得 Pandas 数据框,如下所示:

Given dataframe

我尝试使用 json_normalize ,但没有成功。

最佳答案

正确处理嵌套 JSON 总是相当棘手。

几个月前,我想出了一种方法,使用 here 中编写精美的 flatten_json_iterative_solution 来提供“通用答案”。 :迭代地解包给定 json 的每个级别。

然后可以简单地将其转换为 Pandas.Series,然后 Pandas.DataFrame,如下所示:

df = pd.Series(flatten_json_iterative_solution(dict(json_))).to_frame().reset_index()

Intermediate Dataframe result

可以轻松执行一些数据转换来拆分您要求的列名称中的索引:

df[["index", "col1", "col2", "col3", "col4"]] = df['index'].apply(lambda x: pd.Series(x.split('_')))

Final result

关于python - 将 JSON 文件转换为 Pandas 数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58694092/

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