Pandas 是 Python 最常用的資料分析套件,to_json()
和 to_dict()
則是 DataFrame 轉換成 Python 原生物件或 JSON 格式的超實用工具。不論你要跟前端溝通、存檔、或是傳給 API,都會用到。這篇用簡單範例帶你一次搞懂這兩個方法的用法、參數、和常見錯誤!
一、準備一個簡單的 DataFrame
import pandas as pd
df = pd.DataFrame({
'name': ['Amy', 'Brian'],
'score': [90, 85]
})
print(df)
輸出結果:


二、to_dict()
的用法與 orient 參數
預設用法(orient="dict"
)
d = df.to_dict()
print(d)
輸出結果:
不論有沒有寫orient="dict"
輸出結果都一樣
常見 orient
參數:
orient:
最常用的是 "records"
:
records = df.to_dict(orient="records")
#List[dict]
print(records)
# [{'name': 'Amy', 'score': 90}, {'name': 'Brian', 'score': 85}]
三、to_json()
的用法與 orient 參數
預設用法(orient="columns"
)
j = df.to_json()
print(j)
輸出結果:
(這不是最直覺的格式)
最常用 orient="records"
j = df.to_json(orient="records", force_ascii=False)
print(j)
輸出結果:
這種格式最適合前端、API、NoSQL 交換。
四、常見錯誤與解法
1. 縮排問題:
df.to_json()
產生的 JSON 字串沒縮排。- 如果你想要縮排、好閱讀的 JSON,應該先轉成
to_dict()
,再用json.dump()
輸出:
import json
data = df.to_dict(orient="records")
with open("output.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
2. MultiIndex 錯誤:
- 如果你的 DataFrame 欄位名稱是 tuple(多層欄位),
to_dict()
轉 JSON 會報錯。 - 解法:請平坦化欄位名稱
#1. 只保留 tuple 的第一層欄位名
df.columns = [col[0] if isinstance(col, tuple) else col for col in df.columns]
#2. 用 join 合併所有欄位層級
df.columns = ['_'.join(map(str, col)) if isinstance(col, tuple) else col for col in df.columns]
用 join 合併所有欄位層級:
五、總結與選擇建議
- 交換資料給前端/API → 用
to_json(orient="records")
或to_dict(orient="records")
- 要寫成美觀的 JSON 檔案 → 先
to_dict(orient="records")
,再用json.dump(..., indent=4)
- 表格欄位有多層 → 記得先平坦化欄位名稱
六、常用小抄
# DataFrame 轉 Python 物件 (list of dict)
data = df.to_dict(orient="records")
# DataFrame 直接轉 JSON 字串
json_str = df.to_json(orient="records", force_ascii=False)
# 美觀輸出 JSON 檔案
import json
with open("output.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
七、延伸閱讀
推薦hahow線上學習python: https://igrape.net/30afN