Python - How to convert JSON File to Dataframe

匿名 (未验证) 提交于 2019-12-03 01:33:01

问题:

How can I convert a JSON File as such into a dataframe to do some transformations.

For Example if the JSON file reads:

{"FirstName":"John",  "LastName":"Mark",  "MiddleName":"Lewis",  "username":"johnlewis2",  "password":"2910"} 

How can I convert it to a table like such

Column -> FirstName | LastName | MiddleName | username | password    Row ----->    John | Mark |Lewis | johnlewis2 |2910 

回答1:

Creating dataframe from dictionary object.

import pandas as pd data = [{'name': 'vikash', 'age': 27}, {'name': 'Satyam', 'age': 14}] df = pd.DataFrame.from_dict(data, orient='columns')  df Out[4]:    age  name 0   27  vikash 1   14  Satyam 

If you have nested columns then you first need to normalize the data:

from pandas.io.json import json_normalize data = [   {     'name': {       'first': 'vikash',       'last': 'singh'     },     'age': 27   },   {     'name': {       'first': 'satyam',       'last': 'singh'     },     'age': 14   } ]  df = pd.DataFrame.from_dict(json_normalize(data), orient='columns')  df     Out[8]: age name.first  name.last 0   27  vikash  singh 1   14  satyam  singh 

Source: https://github.com/vi3k6i5/pandas_basics/blob/master/1_a_create_a_dataframe_from_dictonary.ipynb



回答2:

from pandas.io.json import json_normalize print json_normalize(your_json) 

This will Normalize semi-structured JSON data into a flat table

Output

  FirstName LastName MiddleName password    username       John     Mark      Lewis     2910  johnlewis2 


回答3:

jsondata = '{"0001":{"FirstName":"John","LastName":"Mark","MiddleName":"Lewis","username":"johnlewis2","password":"2910"}}' import json import pandas as pd jdata = json.loads(jsondata) df = pd.DataFrame(jdata) print df.T 

This should look like this:.

          FirstName LastName MiddleName password    username 0001      John     Mark      Lewis     2910  johnlewis2 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!