將 JSON 字串載入到 Pandas DataFrame 中
簡介
理解、淨化和處理資料以獲得有洞察力的知識並做出明智的判斷是資料科學和機器學習的藝術。Python 強大的模組(如 Pandas 和 json)使這項工作變得更加簡單。JSON(代表 JavaScript 物件表示法)是一種流行的 Web 資料交換標準。另一方面,Pandas DataFrame 提供了一個有效的結構來儲存和操作 Python 中的表格資料。
本文提供了一個完整的教程,其中包含有用的示例,介紹如何將 JSON 字串匯入到 Pandas DataFrame 中。
先決條件
確保您的 Python 環境已安裝 Pandas 和 json 庫。您可以使用 pip 安裝它們
pip install pandas
將 JSON 字串載入到 Pandas DataFrame 中
示例 1:載入簡單的 JSON 字串
讓我們從一個簡單的 JSON 字串開始。在將 JSON 文字載入到 DataFrame 之前,Python 中的 json 模組首先會將其轉換為 Python 字典。
import pandas as pd
import json
# JSON string
json_string = '{"name": "John", "age": 30, "city": "New York"}'
# Convert JSON string to Python dictionary
data = json.loads(json_string)
# Convert dictionary to DataFrame
df = pd.DataFrame(data, index=[0])
print(df)
輸出
name age city 0 John 30 New York
示例 2:載入包含多個物件的 JSON 字串
現在讓我們處理一個包含多個物件的 JSON 字串。在這種情況下,DataFrame 中的每一行都對應於 JSON 文字中的一個物件。
import pandas as pd
import json
# JSON string
json_string = '[{"name": "John", "age": 30, "city": "New York"},{"name": "Jane", "age": 25, "city": "Chicago"}]'
# Convert JSON string to Python list of dictionaries
data = json.loads(json_string)
# Convert list of dictionaries to DataFrame
df = pd.DataFrame(data)
print(df)
輸出
name age city 0 John 30 New York 1 Jane 25 Chicago
示例 3:載入巢狀的 JSON 字串
巢狀的 JSON 字串需要稍微複雜一些的處理。可以將每個巢狀物件視為一個單獨的 DataFrame,可以將其與主 DataFrame 合併。
import pandas as pd
import json
# Nested JSON string
json_string = '{"employee":{"name": "John", "age": 30, "city": "New York"}, "company":{"name": "ABC Corp", "location": "USA"}}'
# Convert JSON string to Python dictionary
data = json.loads(json_string)
# Convert each nested dictionary to a DataFrame and merge
df_employee = pd.DataFrame(data['employee'], index=[0])
df_company = pd.DataFrame(data['company'], index=[0])
df = pd.concat([df_employee, df_company], axis=1)
print(df)
輸出
name age city name location 0 John 30 New York ABC Corp USA
由於它存在於兩個巢狀字典中,“name”列在該 DataFrame 中出現兩次。請確保正確重新命名列以避免混淆。
結論
在 Python 中處理 Web 資料時,一個常見的操作是將 JSON 字串載入到 Pandas DataFrame 中。即使是複雜的 JSON 字串,也可以使用 Pandas 和 json 包有效地載入到 DataFrame 中,以進行進一步的資料分析和操作。
如果您瞭解如何將 JSON 字串載入到 DataFrame 中,那麼您將擁有一個堅實的基礎來挖掘 JSON 資料以獲得見解。憑藉這些知識,您可以更有效地載入、處理和視覺化資料,從而提高作為資料科學家、資料分析師或機器學習工程師的生產力。由於 JSON 是 Web 上資料傳輸的全球標準,因此這些技能對於許多資料驅動的應用程式和專案都將非常有用。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP