編寫一段 Python 程式碼,從檔案中讀取 JSON 資料並將其轉換為資料框架、CSV 檔案


假設將以下 JSON 示例資料儲存在檔案 pandas_sample.json

{
   "employee": {
      "name": "emp1",
      "salary": 50000,
      "age": 31
   }
}

轉換為 csv 後的結果如下,

,employee
age,31
name,emp1
salary,50000

解決方案

為了解決此問題,我們將按照以下步驟進行 −

  • 建立 pandas_sample.json 檔案並存儲 JSON 資料。

  • 從檔案讀取 json 資料並將其儲存為 data。

data = pd.read_json('pandas_sample.json')
  • 轉換資料為資料框

df = pd.DataFrame(data)
  • Apple df.to_csv 函式將資料轉換為 csv 檔案格式,

df.to_csv('pandas_json.csv')

示例

讓我們看看下面的實現,以獲得更好的理解 -

import pandas as pd
data = pd.read_json('pandas_sample.json')
df = pd.DataFrame(data)
df.to_csv('pandas_json.csv')

輸出

employee
age 31
name emp1
salary 50000

更新於: 24-2 月-2021

980 次訪問

啟動你的 職業生涯

完成課程獲取認證

開始
廣告