pd.json_normalize
是 pandas 库中的一个函数,用于将嵌套的 JSON 数据扁平化为一个表格形式的数据结构,通常是 DataFrame。这个函数在处理复杂的 JSON 数据时非常有用,尤其是当数据包含多层嵌套或者数组时。
JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。JSON 数据通常以键值对的形式表示,可以包含嵌套的对象和数组。
Pandas 是一个 Python 数据分析库,提供了大量的数据结构和数据分析工具,其中 DataFrame 是其核心数据结构之一,类似于表格或 SQL 表。
pd.json_normalize 函数可以将嵌套的 JSON 数据转换为扁平化的 DataFrame,使得每一层嵌套的数据都成为 DataFrame 中的一列。
pd.json_normalize
可以处理以下类型的嵌套 JSON 数据:
假设我们有以下嵌套的 JSON 数据:
nested_json = {
"id": 1,
"name": "John Doe",
"contact": {
"email": "john.doe@example.com",
"phone_numbers": [
{"type": "home", "number": "123-456-7890"},
{"type": "work", "number": "098-765-4321"}
]
},
"orders": [
{"order_id": 101, "product": "Widget", "quantity": 2},
{"order_id": 102, "product": "Gadget", "quantity": 1}
]
}
使用 pd.json_normalize
可以将其扁平化为 DataFrame:
import pandas as pd
# 扁平化嵌套的 JSON 数据
df = pd.json_normalize(nested_json, sep='_')
print(df)
输出结果将是:
id name contact_email contact_phone_numbers_0_type contact_phone_numbers_0_number contact_phone_numbers_1_type contact_phone_numbers_1_number orders_0_order_id orders_0_product orders_0_quantity orders_1_order_id orders_1_product orders_1_quantity
0 1 John Doe john.doe@example.com home 123-456-7890 work 098-765-4321 101 Widget 2 102 Gadget 1
问题:如果 JSON 数据中的某些键不存在,使用 pd.json_normalize
可能会导致 KeyError。
解决方法:在使用 pd.json_normalize
之前,可以先检查 JSON 数据的结构,确保所有预期的键都存在。或者,可以使用 errors='ignore'
参数来忽略不存在的键:
df = pd.json_normalize(nested_json, sep='_', errors='ignore')
这样,即使某些键不存在,也不会引发错误,而是会在结果 DataFrame 中省略这些键对应的列。
通过这种方式,pd.json_normalize
函数可以帮助开发者有效地处理和分析嵌套的 JSON 数据。
领取专属 10元无门槛券
手把手带您无忧上云