您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關如何使用pandas處理json數據,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
json字符串:
strtext='[{"ttery":"min","issue":"20130801-3391","code":"8,4,5,2,9","code1":"297734529","code2":null,"time":1013395466000},\ {"ttery":"min","issue":"20130801-3390","code":"7,8,2,1,2","code1":"298058212","code2":null,"time":1013395406000},\ {"ttery":"min","issue":"20130801-3389","code":"5,9,1,2,9","code1":"298329129","code2":null,"time":1013395346000},\ {"ttery":"min","issue":"20130801-3388","code":"3,8,7,3,3","code1":"298588733","code2":null,"time":1013395286000},\ {"ttery":"min","issue":"20130801-3387","code":"0,8,5,2,7","code1":"298818527","code2":null,"time":1013395226000}]'
pandas.read_json的語法如下:
pandas.read_json(path_or_buf=None, orient=None, typ='frame', dtype=True, convert_axes=True, convert_dates=True, keep_default_dates=True, numpy=False, precise_float=False, date_unit=None, encoding=None, lines=False, chunksize=None, compression='infer')
第一參數就是json文件路徑或者json格式的字符串。
第二參數orient是表明預期的json字符串格式。orient的設置有以下幾個值:
(1).'split' : dict like {index -> [index], columns -> [columns], data -> [values]}
這種就是有索引,有列字段,和數據矩陣構成的json格式。key名稱只能是index,columns和data。
'records' : list like [{column -> value}, ... , {column -> value}]
這種就是成員為字典的列表。如我今天要處理的json數據示例所見。構成是列字段為鍵,值為鍵值,每一個字典成員就構成了dataframe的一行數據。
'index' : dict like {index -> {column -> value}}
以索引為key,以列字段構成的字典為鍵值。如:
'columns' : dict like {column -> {index -> value}}
這種處理的就是以列為鍵,對應一個值字典的對象。這個字典對象以索引為鍵,以值為鍵值構成的json字符串。如下圖所示:
'values' : just the values array。
values這種我們就很常見了。就是一個嵌套的列表。里面的成員也是列表,2層的。
主要就說下這兩個參數吧。下面我們回到示例中來。我們看前面可以發現示例是一個orient為records的json字符串。
這樣就好處理了。看代碼:
# -*- coding: utf-8 -*- """ Created on Sun Aug 5 09:01:38 2018 @author: FanXiaoLei """ import pandas as pd strtext='[{"ttery":"min","issue":"20130801-3391","code":"8,4,5,2,9","code1":"297734529","code2":null,"time":1013395466000},\ {"ttery":"min","issue":"20130801-3390","code":"7,8,2,1,2","code1":"298058212","code2":null,"time":1013395406000},\ {"ttery":"min","issue":"20130801-3389","code":"5,9,1,2,9","code1":"298329129","code2":null,"time":1013395346000},\ {"ttery":"min","issue":"20130801-3388","code":"3,8,7,3,3","code1":"298588733","code2":null,"time":1013395286000},\ {"ttery":"min","issue":"20130801-3387","code":"0,8,5,2,7","code1":"298818527","code2":null,"time":1013395226000}]' df=pd.read_json(strtext,orient='records') df.to_excel('pandas處理json.xlsx',index=False,columns=["ttery","issue","code","code1","code2","time"])
最終寫入excel如下圖:
關于如何使用pandas處理json數據就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。