Python Pandas - 讀取和寫入JSON檔案



Pandas庫提供了強大的函式,用於以各種格式讀取和寫入資料。其中一種格式是JSON(JavaScript物件表示法),它是一種輕量級的資料交換格式,易於人工讀取和寫入。JSON廣泛用於在伺服器和Web應用程式之間傳輸資料。

JSON檔案以結構化格式儲存資料,類似於Python中的字典或列表。JSON副檔名為.json。下面您可以看到JSON檔案中資料的樣式:

[
   {
      "Name": "Braund",
      "Gender": "Male",
      "Age": 30
   },
   {
      "Name": "Cumings",
      "Gender": "Female",
      "Age": 25
   },
   {
      "Name": "Heikkinen",
      "Gender": "female",
      "Age": 35
   }
]

在本教程中,我們將學習如何使用Pandas處理JSON檔案,包括讀取和寫入JSON檔案以及一些常見的配置。

讀取JSON檔案

pandas.read_json()函式用於將JSON資料讀取到Pandas DataFrame中。此函式可以接受檔案路徑、URL或JSON字串作為輸入。

示例

以下示例演示瞭如何使用pandas.read_json()函式讀取JSON資料。這裡我們使用StringIO將JSON字串載入到類似檔案的物件中。

import pandas as pd
from io import StringIO

# Create a string representing JSON data
data = """[
   {"Name": "Braund", "Gender": "Male", "Age": 30},
   {"Name": "Cumings", "Gender": "Female", "Age": 25},
   {"Name": "Heikkinen", "Gender": "Female", "Age": 35}
]"""

# Use StringIO to convert the JSON formatted string data into a file-like object
obj = StringIO(data)

# Read JSON into a Pandas DataFrame
df = pd.read_json(obj)

print(df)

以下是上述程式碼的輸出:

Name Gender Age
0 Braund Male 30
1 Cumings Female 25
2 Heikkinen Female 35

寫入JSON檔案

Pandas提供.to_json()函式,可以使用Pandas DataFrame或Series物件中的資料來寫入或建立JSON檔案。此函式用於將Pandas資料結構物件轉換為JSON字串,並允許您使用多個引數自定義JSON輸出的格式。

示例:寫入JSON檔案的基本示例

這是一個演示如何將Pandas DataFrame寫入JSON檔案的示例。

import pandas as pd

# Create a DataFrame from the above dictionary
df = pd.DataFrame({"Name":["Braund", "Cumings", "Heikkinen"], 
"Gender": ["Male", "Female", "Female"],
"Age": [30, 25, 25]})
print("Original DataFrame:\n", df)   

# Write DataFrame to a JSON file
df.to_json("output_written_json_file.json", orient='records', lines=True)

print("The output JSON file has been written successfully.")

以下是上述程式碼的輸出:

Original DataFrame:
Name Gender Age
0 Braund Male 30
1 Cumings Female 25
2 Heikkinen Female 35
The output JSON file has been written successfully.

執行上述程式碼後,您可以在工作目錄中找到名為output_written_json_file.json的已建立JSON檔案。

示例:使用split方向寫入JSON檔案

以下示例使用split方向將簡單的DataFrame物件寫入JSON。

import pandas as pd
from json import loads, dumps

# Create a DataFrame
df = pd.DataFrame(
   [["x", "y"], ["z", "w"]],
   index=["row_1", "row_2"],
   columns=["col_1", "col_2"],
)

# Convert DataFrame to JSON with 'split' orientation
result = df.to_json(orient="split")
parsed = loads(result)

# Display the JSON output
print("JSON Output (split orientation):")
print(dumps(parsed, indent=4))

以下是上述程式碼的輸出:

JSON Output (split orientation):
{
   "columns": [
      "col_1",
      "col_2"
   ],
   "index": [
      "row_1",
      "row_2"
   ],
   "data": [
      [
         "x",
         "y"
      ],
      [
         "z",
         "w"
      ]
   ]
}
廣告