Pandas JSON的處理使用
JSON(JavaScript Object Notation,JavaScript 對(duì)象表示法),是存儲(chǔ)和交換文本信息的語法,類似 XML。JSON 比 XML 更小、更快,更易解析。Pandas 提供了強(qiáng)大的方法來處理 JSON 格式的數(shù)據(jù),支持從 JSON 文件或字符串中讀取數(shù)據(jù)并將其轉(zhuǎn)換為 DataFrame,以及將 DataFrame 轉(zhuǎn)換回 JSON 格式。
操作 | 方法 | 說明 |
---|---|---|
從 JSON 文件/字符串讀取數(shù)據(jù) | pd.read_json() | 從 JSON 數(shù)據(jù)中讀取并加載為 DataFrame |
將 DataFrame 轉(zhuǎn)換為 JSON | DataFrame.to_json() | 將 DataFrame 轉(zhuǎn)換為 JSON 格式的數(shù)據(jù),可以指定結(jié)構(gòu)化方式 |
支持 JSON 結(jié)構(gòu)化方式 | orient 參數(shù) | 支持多種結(jié)構(gòu)化方式,如 split 、records 、columns |
Pandas 可以很方便的處理 JSON 數(shù)據(jù),本文以 sites.json 為例,內(nèi)容如下:
[ { "id": "A001", "name": "bing", "url": "www.bing.com", "likes": 61 }, { "id": "A002", "name": "Google", "url": "www.google.com", "likes": 124 }, { "id": "A003", "name": "淘寶", "url": "www.taobao.com", "likes": 45 } ]
1 從 JSON 文件/字符串加載數(shù)據(jù)
1.1 pd.read_json() - 讀取 JSON 數(shù)據(jù)
read_json() 用于從 JSON 格式的數(shù)據(jù)中讀取并加載為一個(gè) DataFrame。它支持從 JSON 文件、JSON 字符串或 JSON 網(wǎng)址中加載數(shù)據(jù)。
df = pd.read_json( path_or_buffer, # JSON 文件路徑、JSON 字符串或 URL orient=None, # JSON 數(shù)據(jù)的結(jié)構(gòu)方式,默認(rèn)是 'columns' dtype=None, # 強(qiáng)制指定列的數(shù)據(jù)類型 convert_axes=True, # 是否轉(zhuǎn)換行列索引 convert_dates=True, # 是否將日期解析為日期類型 keep_default_na=True # 是否保留默認(rèn)的缺失值標(biāo)記 )
參數(shù) | 說明 | 默認(rèn)值 |
---|---|---|
path_or_buffer | JSON 文件的路徑、JSON 字符串或 URL | 必需參數(shù) |
orient | 定義 JSON 數(shù)據(jù)的格式方式。常見值有 split 、records 、index 、columns 、values 。 | None (根據(jù)文件自動(dòng)推斷) |
dtype | 強(qiáng)制指定列的數(shù)據(jù)類型 | None |
convert_axes | 是否將軸轉(zhuǎn)換為合適的數(shù)據(jù)類型 | True |
convert_dates | 是否將日期解析為日期類型 | True |
keep_default_na | 是否保留默認(rèn)的缺失值標(biāo)記(如 NaN ) | True |
常見的 orient 參數(shù)選項(xiàng):
orient 值 | JSON 格式示例 | 描述 |
---|---|---|
split | {"index":["a","b"],"columns":["A","B"],"data":[[1,2],[3,4]]} | 使用鍵 index 、columns 和 data 結(jié)構(gòu) |
records | [{"A":1,"B":2},{"A":3,"B":4}] | 每個(gè)記錄是一個(gè)字典,表示一行數(shù)據(jù) |
index | {"a":{"A":1,"B":2},"b":{"A":3,"B":4}} | 使用索引為鍵,值為字典的方式 |
columns | {"A":{"a":1,"b":3},"B":{"a":2,"b":4}} | 使用列名為鍵,值為字典的方式 |
values | [[1,2],[3,4]] | 只返回?cái)?shù)據(jù),不包括索引和列名 |
從 JSON 文件加載數(shù)據(jù),to_string() 用于返回 DataFrame 類型的數(shù)據(jù),我們也可以直接處理 JSON 字符串。
import pandas as pd df = pd.read_json('sites.json') print(df.to_string())
JSON 對(duì)象與 Python 字典具有相同的格式,所以我們可以直接將 Python 字典轉(zhuǎn)化為 DataFrame 數(shù)據(jù):
import pandas as pd # 字典格式的 JSON s = { "col1": {"row1": 1, "row2": 2, "row3": 3}, "col2": {"row1": "x", "row2": "y", "row3": "z"} } # 讀取 JSON 轉(zhuǎn)為 DataFrame df = pd.DataFrame(s) print(df)
從 JSON 字符串加載數(shù)據(jù):
from io import StringIO import pandas as pd # JSON 字符串 json_data = ''' [ {"Name": "Alice", "Age": 25, "City": "New York"}, {"Name": "Bob", "Age": 30, "City": "Los Angeles"}, {"Name": "Charlie", "Age": 35, "City": "Chicago"} ] ''' # 從 JSON 字符串讀取數(shù)據(jù) df = pd.read_json(StringIO(json_data)) print(df)
1.2 內(nèi)嵌的 JSON 數(shù)據(jù)
假設(shè)有一組內(nèi)嵌的 JSON 數(shù)據(jù)文件 nested_list.json :
{ "school_name": "ABC primary school", "class": "Year 1", "students": [ { "id": "A001", "name": "Tom", "math": 60, "physics": 66, "chemistry": 61 }, { "id": "A002", "name": "James", "math": 89, "physics": 76, "chemistry": 51 }, { "id": "A003", "name": "Jenny", "math": 79, "physics": 90, "chemistry": 78 }] }
使用以下代碼格式化完整內(nèi)容:
import pandas as pd df = pd.read_json('nested_list.json') print(df)
這時(shí)我們就需要使用到 json_normalize() 方法將內(nèi)嵌的數(shù)據(jù)完整的解析出來:
import pandas as pd import json # 使用 Python JSON 模塊載入數(shù)據(jù) with open('nested_list.json', 'r') as f: data = json.loads(f.read()) # 展平數(shù)據(jù) df_nested_list = pd.json_normalize(data, record_path=['students']) print(df_nested_list)
data = json.loads(f.read()) 使用 Python JSON 模塊載入數(shù)據(jù)。json_normalize() 使用了參數(shù) record_path 并設(shè)置為 ['students'] 用于展開內(nèi)嵌的 JSON 數(shù)據(jù) students。顯示結(jié)果還沒有包含 school_name 和 class 元素,如果需要展示出來可以使用 meta 參數(shù)來顯示這些元數(shù)據(jù):
import pandas as pd import json # 使用 Python JSON 模塊載入數(shù)據(jù) with open('nested_list.json', 'r') as f: data = json.loads(f.read()) # 展平數(shù)據(jù) df_nested_list = pd.json_normalize( data, record_path=['students'], meta=['school_name', 'class'] ) print(df_nested_list)
接下來嘗試讀取更復(fù)雜的 JSON 數(shù)據(jù),該數(shù)據(jù)嵌套了列表和字典,數(shù)據(jù)文件 nested_mix.json 如下:
{ "school_name": "local primary school", "class": "Year 1", "info": { "president": "John Kasich", "address": "ABC road, London, UK", "contacts": { "email": "admin@e.com", "tel": "123456789" } }, "students": [ { "id": "A001", "name": "Tom", "math": 60, "physics": 66, "chemistry": 61 }, { "id": "A002", "name": "James", "math": 89, "physics": 76, "chemistry": 51 }, { "id": "A003", "name": "Jenny", "math": 79, "physics": 90, "chemistry": 78 } ] }
nested_mix.json 文件轉(zhuǎn)換為 DataFrame:
import pandas as pd import json # 使用 Python JSON 模塊載入數(shù)據(jù) with open('nested_mix.json', 'r') as f: data = json.loads(f.read()) df = pd.json_normalize( data, record_path=['students'], meta=[ 'class', ['info', 'president'], ['info', 'contacts', 'tel'] ] ) print(df)
1.3 讀取內(nèi)嵌數(shù)據(jù)中的一組數(shù)據(jù)
以下是實(shí)例文件 nested_deep.json,我們只讀取內(nèi)嵌中的 math 字段:
{ "school_name": "local primary school", "class": "Year 1", "students": [ { "id": "A001", "name": "Tom", "grade": { "math": 60, "physics": 66, "chemistry": 61 } }, { "id": "A002", "name": "James", "grade": { "math": 89, "physics": 76, "chemistry": 51 } }, { "id": "A003", "name": "Jenny", "grade": { "math": 79, "physics": 90, "chemistry": 78 } } ] }
這里我們需要使用到 glom 模塊來處理數(shù)據(jù)套嵌,glom 模塊允許我們使用 . 來訪問內(nèi)嵌對(duì)象的屬性。第一次使用我們需要安裝 glom:
pip3 install glom
import pandas as pd from glom import glom df = pd.read_json('nested_deep.json') data = df['students'].apply(lambda row: glom(row, 'grade.math')) print(data)
2 將 DataFrame 轉(zhuǎn)換為 JSON
2.1 DataFrame.to_json() - 將 DataFrame 轉(zhuǎn)換為 JSON 數(shù)據(jù)
to_json() 方法用于將 DataFrame 轉(zhuǎn)換為 JSON 格式的數(shù)據(jù),可以指定 JSON 的結(jié)構(gòu)化方式。語法格式:
df.to_json( path_or_buffer=None, # 輸出的文件路徑或文件對(duì)象,如果是 None 則返回 JSON 字符串 orient=None, # JSON 格式方式,支持 'split', 'records', 'index', 'columns', 'values' date_format=None, # 日期格式,支持 'epoch', 'iso' default_handler=None, # 自定義非標(biāo)準(zhǔn)類型的處理函數(shù) lines=False, # 是否將每行數(shù)據(jù)作為一行(適用于 'records' 或 'split') encoding='utf-8' # 編碼格式 )
參數(shù) | 說明 | 默認(rèn)值 |
---|---|---|
path_or_buffer | 輸出的文件路徑或文件對(duì)象,若為 None ,則返回 JSON 字符串 | None |
orient | 指定 JSON 格式結(jié)構(gòu),支持 split 、records 、index 、columns 、values | None (默認(rèn)是 columns ) |
date_format | 日期格式,支持 'epoch' 或 'iso' 格式 | None |
default_handler | 自定義處理非標(biāo)準(zhǔn)類型(如 datetime 等)的處理函數(shù) | None |
lines | 是否將每行數(shù)據(jù)作為一行輸出(適用于 records 或 split ) | False |
encoding | 輸出文件的編碼格式 | 'utf-8' |
import pandas as pd # 創(chuàng)建 DataFrame df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['New York', 'Los Angeles', 'Chicago'] }) # 將 DataFrame 轉(zhuǎn)換為 JSON 字符串 json_str = df.to_json() print(json_str)
將 DataFrame 轉(zhuǎn)換為 JSON 文件(指定 orient='records'):
import pandas as pd # 創(chuàng)建 DataFrame df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['New York', 'Los Angeles', 'Chicago'] }) # 將 DataFrame 轉(zhuǎn)換為 JSON 文件,指定 orient='records' df.to_json('data.json', orient='records', lines=True)
將 DataFrame 轉(zhuǎn)換為 JSON 并指定日期格式:
import pandas as pd # 創(chuàng)建 DataFrame,包含日期數(shù)據(jù) df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Date': pd.to_datetime(['2021-01-01', '2022-02-01', '2023-03-01']), 'Age': [25, 30, 35] }) # 將 DataFrame 轉(zhuǎn)換為 JSON,并指定日期格式為 'iso' json_str = df.to_json(date_format='iso') print(json_str)
到此這篇關(guān)于Pandas JSON的處理使用的文章就介紹到這了,更多相關(guān)Pandas JSON內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python基于pandas實(shí)現(xiàn)json格式轉(zhuǎn)換成dataframe的方法
- 對(duì)pandas處理json數(shù)據(jù)的方法詳解
- Pandas讀存JSON數(shù)據(jù)操作示例詳解
- 讀Json文件生成pandas數(shù)據(jù)框詳情
- python使用pandas讀取json文件并進(jìn)行刷選導(dǎo)出xlsx文件的方法示例
- Pandas實(shí)現(xiàn)解析JSON數(shù)據(jù)與導(dǎo)出的示例詳解
- Python?Pandas實(shí)現(xiàn)將嵌套JSON數(shù)據(jù)轉(zhuǎn)換DataFrame
- pandas讀取HTML和JSON數(shù)據(jù)的實(shí)現(xiàn)示例
- Python使用pandas讀取Excel并選取列轉(zhuǎn)json
相關(guān)文章
python環(huán)境的報(bào)錯(cuò)解決方法
這篇文章主要為大家介紹了python環(huán)境的報(bào)錯(cuò)解決方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08Python中實(shí)現(xiàn)遠(yuǎn)程調(diào)用(RPC、RMI)簡單例子
說白了,遠(yuǎn)程調(diào)用就是將對(duì)象名、函數(shù)名、參數(shù)等傳遞給遠(yuǎn)程服務(wù)器,服務(wù)器將處理結(jié)果返回給客戶端2014-04-04利用Python中?Rembg庫實(shí)現(xiàn)去除圖片背景
這篇文章主要介紹了利用Python中?Rembg庫實(shí)現(xiàn)去除圖片背景,文章基于?Rembg庫得運(yùn)用展開詳細(xì)介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-05-05python切片復(fù)制列表的知識(shí)點(diǎn)詳解
在本篇文章里小編給大家整理的是一篇關(guān)于python切片復(fù)制列表的知識(shí)點(diǎn)相關(guān)內(nèi)容,有興趣的朋友們可以跟著學(xué)習(xí)下。2021-10-10python對(duì)excel文檔去重及求和的實(shí)例
下面小編就為大家分享一篇python對(duì)excel文檔去重及求和的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-04-04Python使用mmap實(shí)現(xiàn)內(nèi)存映射文件操作
內(nèi)存映射通??梢蕴岣逫/O的性能,本文主要介紹了Python使用mmap實(shí)現(xiàn)內(nèi)存映射文件操作,分享給大家,感興趣的可以了解一下2021-06-06