JSON文件以可读的格式将数据存储为文本。 JSON代表JavaScript Object Notation。 使用read_json函数,Pandas可以读取JSON文件。
输入数据
通过将以下数据复制到文本编辑器(如记事本)来创建JSON文件。选择文件类型作为所有文件(.),使用.json扩展名保存文件,假设保存的文件名称为:input.json。
{
"ID":["1","2","3","4","5","6","7","8" ],
"Name":["Rick","Dan","Michelle","Ryan","Gary","Nina","Simon","Guru" ]
"Salary":["623.3","515.2","611","729","843.25","578","632.8","722.5" ],
"StartDate":[ "1/1/2012","9/23/2013","11/15/2014","5/11/2014","3/27/2015","5/21/2013",
"7/30/2013","6/17/2014"],
"Dept":[ "IT","Operations","IT","HR","Finance","IT","Operations","Finance"]
}
读取JSON文件
Pandas库的read_json函数可用于将JSON文件读入为pandas DataFrame数据结构类型。
import pandas as pd
data = pd.read_json('C:/Users/Administrator/PycharmProjects/myproject/input.json')
print(data)
结果:
Dept ID Name Salary StartDate
0 IT 1 Rick 623.30 1/1/2012
1 Operations 2 Dan 515.20 9/23/2013
2 IT 3 Tusar 611.00 11/15/2014
3 HR 4 Ryan 729.00 5/11/2014
4 Finance 5 Gary 843.25 3/27/2015
5 IT 6 Rasmi 578.00 5/21/2013
6 Operations 7 Pranab 632.80 7/30/2013
7 Finance 8 Guru 722.50 6/17/2014
读写json文件:
import json
file = open('test.json','w',encoding='utf-8')
data1 = {'name':'john','age':12}
data2 = {'name':'merry','age':13}
data = [data1,data2]
print(data)
json.dump(data,file,ensure_ascii=False)
file.close()
file = open('test.json','r',encoding='utf-8')
s = json.load(file)
print (s[0]['name'])
结果:
[{'name': 'john', 'age': 12}, {'name': 'merry', 'age': 13}]
john