【问题标题】:how to flatten out nested json arrays with their parent in python using pandaspython - 如何使用pandas在python中将嵌套的json数组与它们的父级展平
【发布时间】:2021-07-22 17:47:22
【问题描述】:

我需要使用 pandas 模块在 python 中解析和展平嵌套的 json。

源 JSON:

{
    "people": [{
            "name": "ABC",
            "age": "33",
            "mobile": "44545",
            "location": "hyderabad",
            "interests": [{
                "hobby": "dancing",
                "food": "continental",
                "city": "Paris"
            }]
        },
        {
            "name": "DEF",
            "age": "11",
            "mobile": "12121212",
            "location": "pune",
            "interests": [{
                "hobby": "reading",
                "food": "Pizza",
                "city": "France"
            }]
        }
    ]
}

从上面的json源文件中,我需要得到两个不同的json文件,如下:

输出 JSON 1:

{"name": "ABC", "age": "33", "mobile": "44545", "location": "hyderabad"}
{"name": "DEF", "age": "11","mobile": "12121212", "location": "pune”}

输出 JSON 2:

{"name": "ABC”, ”interests_hobby”:”dancing”, “interests_food”:”continental”, “interests_city”:”Paris”}
{“name": "DEF”, ”interests_hobby”:”reading”, “interests_food”:”Pizza”, “interests_city”:”France”}

条件是我们必须使用python和pandas模块。(pd.json_normalize)

【问题讨论】:

  • 到目前为止你尝试过什么?请发布您的代码

标签: python json pandas


【解决方案1】:

首先,您必须打开 json 文件并加载它。然后,使用命令

df = pd.json_normalize(json_obj, record_path="people")

获取包含所需字段的 DataFrame。如您所见,“兴趣”字段尚未拆分,但您可以重做这些步骤。

为了获得具有所需输出的 ​​json 文件,我推荐你

df.to_json(orient='records')

从 DataFrame 返回一个没有索引的 json 文件。

【讨论】:

  • 然后df.explode() 将展平阵列。将要展平的列名称作为 arg 传递。
猜你喜欢
  • 2017-06-19
  • 2021-12-31
  • 2022-06-21
  • 1970-01-01
  • 1970-01-01
  • 2020-03-11
  • 2021-04-27
  • 2019-12-22
  • 2020-02-25
相关资源
最近更新 更多