
本文旨在指导读者如何使用 Pandas 库中的 `json_normalize` 函数处理包含嵌套列表的 JSON 文件,将其转换为易于分析的表格数据。我们将详细介绍如何针对不同的嵌套层级进行展平操作,并演示如何将展平后的数据合并成一个完整的 DataFrame。通过本文的学习,读者将能够有效地处理复杂的 JSON 数据,并将其应用于实际的数据分析任务中。
首先,确保你已经安装了 Pandas 库。如果没有安装,可以使用 pip 进行安装:
pip install pandas
假设我们有一个名为 data.json 的 JSON 文件,内容如下:
[{
"uuid": "a2d89c9b-6e2e-4e3a-8d60-bf3ce2fe3fda",
"timestamp": "2023-11-23 00:26:31.851000 UTC",
"process_timestamp": "2023-11-23 00:26:32.326000 UTC",
"visitor_id": "oeu1700282566730r0.9025758502018271",
"session_id": "AUTO",
"account_id": "25408250069",
"experiments": {
"list": [{
"element": {
"campaign_id": "26314710187",
"experiment_id": "26322360336",
"variation_id": "26314800349",
"is_holdback": "false"
}
}]
},
"entity_id": "25754820685",
"attributes": {
"list": [{
"element": {
"id": null,
"name": "",
"type": "browserId",
"value": "gc"
}
}, {
"element": {
"id": null,
"name": "",
"type": "campaign",
"value": "blablabla"
}
}, {
"element": {
"id": null,
"name": "",
"type": "device",
"value": "desktop"
}
}, {
"element": {
"id": null,
"name": "",
"type": "device_type",
"value": "desktop_laptop"
}
}, {
"element": {
"id": null,
"name": "",
"type": "referrer",
"value": "https://bookings.perrito.com/21df6542"
}
}, {
"element": {
"id": null,
"name": "",
"type": "source_type",
"value": "campaign"
}
}, {
"element": {
"id": null,
"name": "",
"type": "currentTimestamp",
"value": "1700699073915"
}
}, {
"element": {
"id": null,
"name": "",
"type": "offset",
"value": "300"
}
}]
},
"user_ip": "72.38.10.0",
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36",
"referer": "https://bookings.perrito.com/",
"event_type": "other",
"event_name": "transaction",
"revenue": "240939",
"value": null,
"quantity": null,
"tags": {
"key_value": [{
"key": "tour_id",
"value": "386"
}, {
"key": "booking_id",
"value": "123456"
}, {
"key": "payment_type",
"value": "creditcard"
}, {
"key": "revenue",
"value": "240939"
}, {
"key": "pax",
"value": "1"
}, {
"key": "tour_name",
"value": "Best Viaje ever"
}, {
"key": "extras",
"value": "245.00"
}]
},
"revision": "859",
"client_engine": "js",
"client_version": "0.188.1",
"element": {
"campaign_id": "26314710187",
"experiment_id": "26322360336",
"variation_id": "26314800349",
"is_holdback": "false"
}
}]使用以下代码加载 JSON 数据:
import json
import pandas as pd
with open("data.json", "r") as f:
data = json.load(f)json_normalize 函数可以将 JSON 数据展平为表格形式。对于包含嵌套列表的 JSON,我们需要指定 record_path 参数来告诉函数需要展平的列表路径。
首先,定义一些顶层字段作为元数据,这些字段将作为索引字段保留在展平后的数据中:
meta = [
"uuid",
"timestamp",
"process_timestamp",
"visitor_id",
"session_id",
"account_id",
"entity_id",
"user_ip",
"user_agent",
"referer",
"event_type",
"event_name",
"revenue",
"value",
"quantity",
"revision",
"client_engine",
"client_version",
]接下来,针对 experiments.list、attributes.list 和 tags.key_value 这三个嵌套列表分别进行展平:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
experiments_list = pd.json_normalize(
data=data,
record_path=["experiments", "list"],
meta=meta,
record_prefix="experiments.list.",
)
attributes_list = pd.json_normalize(
data=data,
record_path=["attributes", "list"],
meta=meta,
record_prefix="attributes.list.",
)
tags_key_value = pd.json_normalize(
data=data,
record_path=["tags", "key_value"],
meta=meta,
record_prefix="tags.key_value.",
)在上述代码中,record_path 参数指定了需要展平的列表路径,meta 参数指定了需要保留的元数据字段,record_prefix 参数用于为展平后的字段添加前缀,避免命名冲突。
展平后的数据分别存储在 experiments_list、attributes_list 和 tags_key_value 三个 DataFrame 中。为了将这些数据合并成一个完整的 DataFrame,可以使用 pd.merge 函数:
out = (
pd.merge(left=experiments_list, right=attributes_list, on=meta)
.merge(right=tags_key_value, on=meta)
)pd.merge 函数根据指定的元数据字段将 DataFrame 进行合并。注意,由于每个嵌套列表的长度可能不同,合并后的 DataFrame 可能会出现重复的行。
以下是完整的示例代码:
import json
import pandas as pd
with open("data.json", "r") as f:
data = json.load(f)
meta = [
"uuid",
"timestamp",
"process_timestamp",
"visitor_id",
"session_id",
"account_id",
"entity_id",
"user_ip",
"user_agent",
"referer",
"event_type",
"event_name",
"revenue",
"value",
"quantity",
"revision",
"client_engine",
"client_version",
]
experiments_list = pd.json_normalize(
data=data,
record_path=["experiments", "list"],
meta=meta,
record_prefix="experiments.list.",
)
attributes_list = pd.json_normalize(
data=data,
record_path=["attributes", "list"],
meta=meta,
record_prefix="attributes.list.",
)
tags_key_value = pd.json_normalize(
data=data,
record_path=["tags", "key_value"],
meta=meta,
record_prefix="tags.key_value.",
)
out = (
pd.merge(left=experiments_list, right=attributes_list, on=meta)
.merge(right=tags_key_value, on=meta)
)
print(out)本文介绍了如何使用 Pandas 库中的 json_normalize 函数处理包含嵌套列表的 JSON 文件。通过指定 record_path 和 meta 参数,我们可以将 JSON 数据展平为表格形式,并使用 pd.merge 函数将展平后的数据合并成一个完整的 DataFrame。掌握这些技巧可以帮助我们更有效地处理复杂的 JSON 数据,并将其应用于实际的数据分析任务中。
以上就是使用 Pandas json_normalize 展平嵌套 JSON 数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号