
本文旨在指导读者如何使用 Pandas 库中的 `json_normalize` 函数处理包含嵌套列表的 JSON 文件,将其转换为易于分析的表格数据。我们将详细介绍如何针对不同的嵌套层级进行展平操作,并演示如何将展平后的数据合并成一个完整的 DataFrame。通过本文的学习,读者将能够有效地处理复杂的 JSON 数据,并将其应用于实际的数据分析任务中。
准备工作
首先,确保你已经安装了 Pandas 库。如果没有安装,可以使用 pip 进行安装:
pip install pandas
加载 JSON 数据
假设我们有一个名为 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 jsonimport pandas as pdwith open("data.json", "r") as f: data = json.load(f)
使用 json_normalize 展平数据
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 这三个嵌套列表分别进行展平:
Find JSON Path Online
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 jsonimport pandas as pdwith 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)
注意事项
在使用 json_normalize 函数时,需要仔细分析 JSON 数据的结构,确定正确的 record_path 和 meta 参数。如果 JSON 数据中包含多个嵌套层级,可能需要多次调用 json_normalize 函数进行展平。合并展平后的数据时,需要注意数据重复的问题,可以根据实际需求进行去重或聚合操作。
总结
本文介绍了如何使用 Pandas 库中的 json_normalize 函数处理包含嵌套列表的 JSON 文件。通过指定 record_path 和 meta 参数,我们可以将 JSON 数据展平为表格形式,并使用 pd.merge 函数将展平后的数据合并成一个完整的 DataFrame。掌握这些技巧可以帮助我们更有效地处理复杂的 JSON 数据,并将其应用于实际的数据分析任务中。
以上就是使用 Pandas json_normalize 展平嵌套 JSON 数据的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/592453.html
微信扫一扫
支付宝扫一扫