gpt4 book ai didi

python - 将嵌套 json 解压到数据框中的有效方法

转载 作者:太空宇宙 更新时间:2023-11-03 20:32:10 27 4
gpt4 key购买 nike

我有一个嵌套的 json,我想将其转换为 pandas 数据框。我能够使用 json_normalize 进行标准化。

但是,数据框中仍然有 json 层,我也想将其解包。我怎样才能以最好的方式做到这一点?我可能需要在我当前正在做的项目中多次处理这个问题

我的 json 如下

{
"data": {
"allOpportunityApplication": {
"data": [
{
"id": "111111111",
"opportunity": {
"programme": {
"short_name": "XX"
}
},
"person": {
"home_lc": {
"name": "NAME"
}
},
"standards": [
{
"constant_name": "constant1",
"standard_option": {
"option": "true"
}
},
{
"constant_name": "constant2",
"standard_option": {
"option": "true"
}
}
]
}
]
}
}
}

使用json_normalize

standards_df = json_normalize(
standard_json['allOpportunityApplication']['data'],
record_path=['standards'],
meta=['id','person','opportunity']
)

这样我就得到了一个包含以下列的数据框:constant_namestandard_optionidperson机会。问题是数据 standard_optionpersonopportunity 是 json,里面只有一个选项。

每列的当前输出和预期输出如下

标准选项

当前“standard_option”列中的项目如下所示:

{'option': 'true'}  

我希望它只是true

当前“person”列中的项目如下所示:

{'programme': {'short_name': 'XX'}}

我希望它看起来像:XX

机会

当前“机会”列中的项目如下所示:

{'home_lc': {'name': 'NAME'}}       

我希望它看起来像:NAME

最佳答案

可能不是最好的方法,但我认为它有效。

standards_df['person'] = (standards_df.loc[:, 'person']
.apply(lambda x: x['home_lc']['name']))

standards_df['opportunity'] = (standards_df.loc[:, 'opportunity']
.apply(lambda x: x['programme']['short_name']))
    constant_name   standard_option.option  id          person  opportunity
0 constant1 true 111111111 NAME XX
1 constant2 true 111111111 NAME XX

standard_option 当我运行你的代码时已经很好了

关于python - 将嵌套 json 解压到数据框中的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57422307/

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