Pandas JSON的處理使用
JSON(JavaScript Object Notation,JavaScript 對象表示法),是存儲和交換文本信息的語法,類似 XML。JSON 比 XML 更小、更快,更易解析。Pandas 提供了強大的方法來處理 JSON 格式的數(shù)據(jù),支持從 JSON 文件或字符串中讀取數(shù)據(jù)并將其轉換為 DataFrame,以及將 DataFrame 轉換回 JSON 格式。
操作 | 方法 | 說明 |
---|---|---|
從 JSON 文件/字符串讀取數(shù)據(jù) | pd.read_json() | 從 JSON 數(shù)據(jù)中讀取并加載為 DataFrame |
將 DataFrame 轉換為 JSON | DataFrame.to_json() | 將 DataFrame 轉換為 JSON 格式的數(shù)據(jù),可以指定結構化方式 |
支持 JSON 結構化方式 | orient 參數(shù) | 支持多種結構化方式,如 split 、records 、columns |
Pandas 可以很方便的處理 JSON 數(shù)據(jù),本文以 sites.json 為例,內容如下:
[ { "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ù)中讀取并加載為一個 DataFrame。它支持從 JSON 文件、JSON 字符串或 JSON 網(wǎng)址中加載數(shù)據(jù)。
df = pd.read_json( path_or_buffer, # JSON 文件路徑、JSON 字符串或 URL orient=None, # JSON 數(shù)據(jù)的結構方式,默認是 'columns' dtype=None, # 強制指定列的數(shù)據(jù)類型 convert_axes=True, # 是否轉換行列索引 convert_dates=True, # 是否將日期解析為日期類型 keep_default_na=True # 是否保留默認的缺失值標記 )
參數(shù) | 說明 | 默認值 |
---|---|---|
path_or_buffer | JSON 文件的路徑、JSON 字符串或 URL | 必需參數(shù) |
orient | 定義 JSON 數(shù)據(jù)的格式方式。常見值有 split 、records 、index 、columns 、values 。 | None (根據(jù)文件自動推斷) |
dtype | 強制指定列的數(shù)據(jù)類型 | None |
convert_axes | 是否將軸轉換為合適的數(shù)據(jù)類型 | True |
convert_dates | 是否將日期解析為日期類型 | True |
keep_default_na | 是否保留默認的缺失值標記(如 NaN ) | True |
常見的 orient 參數(shù)選項:
orient 值 | JSON 格式示例 | 描述 |
---|---|---|
split | {"index":["a","b"],"columns":["A","B"],"data":[[1,2],[3,4]]} | 使用鍵 index 、columns 和 data 結構 |
records | [{"A":1,"B":2},{"A":3,"B":4}] | 每個記錄是一個字典,表示一行數(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]] | 只返回數(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 對象與 Python 字典具有相同的格式,所以我們可以直接將 Python 字典轉化為 DataFrame 數(shù)據(jù):
import pandas as pd # 字典格式的 JSON s = { "col1": {"row1": 1, "row2": 2, "row3": 3}, "col2": {"row1": "x", "row2": "y", "row3": "z"} } # 讀取 JSON 轉為 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 內嵌的 JSON 數(shù)據(jù)
假設有一組內嵌的 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 }] }
使用以下代碼格式化完整內容:
import pandas as pd df = pd.read_json('nested_list.json') print(df)
這時我們就需要使用到 json_normalize() 方法將內嵌的數(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 并設置為 ['students'] 用于展開內嵌的 JSON 數(shù)據(jù) students。顯示結果還沒有包含 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)
接下來嘗試讀取更復雜的 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 文件轉換為 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 讀取內嵌數(shù)據(jù)中的一組數(shù)據(jù)
以下是實例文件 nested_deep.json,我們只讀取內嵌中的 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 模塊允許我們使用 . 來訪問內嵌對象的屬性。第一次使用我們需要安裝 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 轉換為 JSON
2.1 DataFrame.to_json() - 將 DataFrame 轉換為 JSON 數(shù)據(jù)
to_json() 方法用于將 DataFrame 轉換為 JSON 格式的數(shù)據(jù),可以指定 JSON 的結構化方式。語法格式:
df.to_json( path_or_buffer=None, # 輸出的文件路徑或文件對象,如果是 None 則返回 JSON 字符串 orient=None, # JSON 格式方式,支持 'split', 'records', 'index', 'columns', 'values' date_format=None, # 日期格式,支持 'epoch', 'iso' default_handler=None, # 自定義非標準類型的處理函數(shù) lines=False, # 是否將每行數(shù)據(jù)作為一行(適用于 'records' 或 'split') encoding='utf-8' # 編碼格式 )
參數(shù) | 說明 | 默認值 |
---|---|---|
path_or_buffer | 輸出的文件路徑或文件對象,若為 None ,則返回 JSON 字符串 | None |
orient | 指定 JSON 格式結構,支持 split 、records 、index 、columns 、values | None (默認是 columns ) |
date_format | 日期格式,支持 'epoch' 或 'iso' 格式 | None |
default_handler | 自定義處理非標準類型(如 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 轉換為 JSON 字符串 json_str = df.to_json() print(json_str)
將 DataFrame 轉換為 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 轉換為 JSON 文件,指定 orient='records' df.to_json('data.json', orient='records', lines=True)
將 DataFrame 轉換為 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 轉換為 JSON,并指定日期格式為 'iso' json_str = df.to_json(date_format='iso') print(json_str)
到此這篇關于Pandas JSON的處理使用的文章就介紹到這了,更多相關Pandas JSON內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- Python基于pandas實現(xiàn)json格式轉換成dataframe的方法
- 對pandas處理json數(shù)據(jù)的方法詳解
- Pandas讀存JSON數(shù)據(jù)操作示例詳解
- 讀Json文件生成pandas數(shù)據(jù)框詳情
- python使用pandas讀取json文件并進行刷選導出xlsx文件的方法示例
- Pandas實現(xiàn)解析JSON數(shù)據(jù)與導出的示例詳解
- Python?Pandas實現(xiàn)將嵌套JSON數(shù)據(jù)轉換DataFrame
- pandas讀取HTML和JSON數(shù)據(jù)的實現(xiàn)示例
- Python使用pandas讀取Excel并選取列轉json
相關文章
Python中實現(xiàn)遠程調用(RPC、RMI)簡單例子
說白了,遠程調用就是將對象名、函數(shù)名、參數(shù)等傳遞給遠程服務器,服務器將處理結果返回給客戶端2014-04-04利用Python中?Rembg庫實現(xiàn)去除圖片背景
這篇文章主要介紹了利用Python中?Rembg庫實現(xiàn)去除圖片背景,文章基于?Rembg庫得運用展開詳細介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-05-05