将多字典从json转换为dataframe

时间:2018-12-11 20:59:42

标签: python json pandas

我相信使用for循环解析JSON会收到以下输出。我想知道如何将输出转换为数据框

01E8jn7u387ZHexw2mOo => {'email': 'a4@yahoo.com ', 
'agreed_to_terms': True, 'toy_duration': 2, 'dog_name': 'Oakley', 
'dog_breeds': ['Mixed Breed / Mutt'], 'zip': '95355', 'human_name': 
'Alina'}
01WCbRaNLVVWglHopTEJ => {'zip': '45014', 'human_name': 'Neil', 
'agreed_to_terms': True, 'email': 'Nek@gmail.com ', 
'toy_duration': 0, 'dog_name': 'Maize, Georgie', 'dog_breeds': ['German 
Shorthaired Lab', 'Shih Tzu']}
02InTOWJSxfjHIPDTPdE => {'agreed_to_terms': True, 'email': 
'2@aol.com', 'toy_duration': 2, 'dog_name': 'Chewie', 
'dog_breeds': ['Shih Tzu'], 'zip': '32068', 'human_name': 'Amber'}

任何帮助将不胜感激。谢谢

2 个答案:

答案 0 :(得分:0)

看起来像是json_normalize的工作。

import json
from pandas.io.json import json_normalize

a = {'email': 'a4@yahoo.com ', 
'agreed_to_terms': True, 'toy_duration': 2, 'dog_name': 'Oakley', 
'dog_breeds': ['Mixed Breed / Mutt'], 'zip': '95355', 'human_name': 
'Alina'}


df_a = json_normalize(a)

答案 1 :(得分:0)

您的意思是这样吗?

>>> data = [
    {
        "email": "a4@yahoo.com ",
        "agreed_to_terms": True,
        "toy_duration": 2,
        "dog_name": "Oakley",
        "dog_breeds": ["Mixed Breed / Mutt"],
        "zip": "95355",
        "human_name": "Alina",
    },
    {
        "zip": "45014",
        "human_name": "Neil",
        "agreed_to_terms": True,
        "email": "Nek@gmail.com ",
        "toy_duration": 0,
        "dog_name": "Maize, Georgie",
        "dog_breeds": ["German Shorthaired Lab", "Shih Tzu"],
    },
    {
        "agreed_to_terms": True,
        "email": "2@aol.com",
        "toy_duration": 2,
        "dog_name": "Chewie",
        "dog_breeds": ["Shih Tzu"],
        "zip": "32068",
        "human_name": "Amber",
    },
]

>>> pd.DataFrame(data)
   agreed_to_terms                          dog_breeds        dog_name           email human_name  toy_duration    zip
0             True                [Mixed Breed / Mutt]          Oakley   a4@yahoo.com       Alina             2  95355
1             True  [German Shorthaired Lab, Shih Tzu]  Maize, Georgie  Nek@gmail.com        Neil             0  45014
2             True                          [Shih Tzu]          Chewie       2@aol.com      Amber             2  32068

积累一条狗的清单,很容易将其变成熊猫数据框。