Python處理Json資料


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('path/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

讀取特定的列和行

與在前一章中已經看到的讀取CSV檔案類似,讀取JSON檔案到DataFrame後,pandas庫的read_json函式也可用於讀取一些特定列和特定行。 使用.loc()的多軸索引方法。選擇顯示salaryname列的某些行。

import pandas as pd
data = pd.read_json('path/input.xlsx')

# Use the multi-axes indexing funtion
print (data.loc[[1,3,5],['salary','name']])

當我們執行上面的程式碼時,它會產生以下結果。

   salary   name
1   515.2    Dan
3   729.0   Ryan
5   578.0  Rasmi

將JSON檔案作為記錄讀取

還可以將to_json函式與引數一起應用於將JSON檔案內容讀入單個記錄。

import pandas as pd
data = pd.read_json('path/input.xlsx')

print(data.to_json(orient='records', lines=True))

執行上面範例程式碼,得到以下結果 -

{"Dept":"IT","ID":1,"Name":"Rick","Salary":623.3,"StartDate":"1\/1\/2012"}
{"Dept":"Operations","ID":2,"Name":"Dan","Salary":515.2,"StartDate":"9\/23\/2013"}
{"Dept":"IT","ID":3,"Name":"Tusar","Salary":611.0,"StartDate":"11\/15\/2014"}
{"Dept":"HR","ID":4,"Name":"Ryan","Salary":729.0,"StartDate":"5\/11\/2014"}
{"Dept":"Finance","ID":5,"Name":"Gary","Salary":843.25,"StartDate":"3\/27\/2015"}
{"Dept":"IT","ID":6,"Name":"Rasmi","Salary":578.0,"StartDate":"5\/21\/2013"}
{"Dept":"Operations","ID":7,"Name":"Pranab","Salary":632.8,"StartDate":"7\/30\/2013"}
{"Dept":"Finance","ID":8,"Name":"Guru","Salary":722.5,"StartDate":"6\/17\/2014"}