字典嵌套展开data = {
"id": 1,
"name": "John",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zip": "10001"
},
"phone_numbers": [
{
"type": "home",
"number": "555-1234"
},
{
"type": "work",
"number": "555-5678"
}
]
}
df = pd.DataFrame([data])
address_df = json_normalize(df['address'])
"""
street city state zip
0 123 Main St New York NY 10001
"""
df = pd.concat([df.drop('address', axis=1), address_df], axis=1)
字典列表展开import pandas as pd
from pandas import json_normalize
data = {
"id": 1,
"name": "John",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zip": "10001"
},
"phone_numbers": [
{
"type": "home",
"number": "555-1234"
},
{
"type": "work",
"number": "555-5678"
}
]
}
df = pd.DataFrame([data])
phone_df = json_normalize(df.to_dict(orient='records'), record_path=['phone_numbers'], meta=['id'], record_prefix='phone_')
"""
phone_type phone_number id
0 home 555-1234 1
1 work 555-5678 1
"""
df = pd.merge(df.drop('phone_numbers', axis=1), phone_df, on='id')