在数据分析领域,Pandas 是一个强大的 Python 库,它提供了丰富的数据处理功能。JSON 数据格式在 Web 开发和数据交换中非常常见,但 JSON 嵌套数据给数据处理带来了挑战。本文将详细介绍如何使用 Pandas 处理 JSON 嵌套数据,帮助您解锁数据分析新技能。
JSON 嵌套数据简介
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于阅读和编写,同时也易于机器解析和生成。JSON 嵌套数据指的是 JSON 对象中包含其他 JSON 对象或数组。
示例
以下是一个 JSON 嵌套数据的示例:
{
“users”: [
{
“id”: 1,
“name”: “Alice”,
“profile”: {
“age”: 28,
“address”: {
“street”: “123 Main St”,
“city”: “Wonderland”
}
}
},
{
“id”: 2,
“name”: “Bob”,
“profile”: {
“age”: 22,
“address”: {
“street”: “456 Elm St”,
“city”: “Nowhere”
}
}
}
]
}
Pandas 处理 JSON 嵌套数据
1. 使用
json_normalize
函数
Pandas 提供了
json_normalize
函数,可以将嵌套的 JSON 数据转换为 DataFrame。
import pandas as pd
import json
json_data = ”’
{
“users”: [
{
“id”: 1,
“name”: “Alice”,
“profile”: {
“age”: 28,
“address”: {
“street”: “123 Main St”,
“city”: “Wonderland”
}
}
},
{
“id”: 2,
“name”: “Bob”,
“profile”: {
“age”: 22,
“address”: {
“street”: “456 Elm St”,
“city”: “Nowhere”
}
}
}
]
}
”’
data = json.loads(json_data)
users_df = pd.json_normalize(data[‘users’], record_path=[‘profile’, ‘address’])
print(users_df)
2. 使用
pd.json_normalize
处理嵌套数组
如果 JSON 数据中的嵌套数组也需要展开,可以使用
record_path
参数。
# 示例 JSON 数据
json_data = ”’
{
“users”: [
{
“id”: 1,
“name”: “Alice”,
“profile”: {
“age”: 28,
“address”: [
{
“street”: “123 Main St”,
“city”: “Wonderland”
},
{
“street”: “789 Oak St”,
“city”: “Elsewhere”
}
]
}
},
{
“id”: 2,
“name”: “Bob”,
“profile”: {
“age”: 22,
“address”: [
{
“street”: “456 Elm St”,
“city”: “Nowhere”
}
]
}
}
]
}
”’
data = json.loads(json_data)
addresses_df = pd.json_normalize(data[‘users’], record_path=[‘profile’, ‘address’])
print(addresses_df)
3. 使用
pd.json_normalize
处理嵌套字典
如果 JSON 数据中的嵌套字典也需要展开,可以使用
meta
参数。
# 示例 JSON 数据
json_data = ”’
{
“users”: [
{
“id”: 1,
“name”: “Alice”,
“profile”: {
“age”: 28,
“address”: {
“street”: “123 Main St”,
“city”: “Wonderland”
}
}
},
{
“id”: 2,
“name”: “Bob”,
“profile”: {
“age”: 22,
“address”: {
“street”: “456 Elm St”,
“city”: “Nowhere”
}
}
}
]
}
”’
data = json.loads(json_data)
profiles_df = pd.json_normalize(data[‘users’], meta=[‘id’, ‘name’], record_path=[‘profile’])
print(profiles_df)
总结
通过本文的介绍,相信您已经掌握了使用 Pandas 处理 JSON 嵌套数据的方法。掌握这些技能,可以帮助您更高效地进行数据分析,从而在数据分析领域取得更好的成绩。