Python Pandas - 使用 CSV 格式



Python 中的 Pandas 庫提供了大量用於讀取和寫入各種格式資料的函式。最常用的格式之一是 CSV(逗號分隔值),它是一種用於儲存表格資料的流行格式。

CSV 檔案是一個純文字檔案,其中資料值以逗號分隔,以純文字格式表示表格資料。CSV 檔案具有.csv副檔名。下面您可以看到 CSV 檔案中的資料是什麼樣的 -

Sr.no,Name,Gender,Age
1,"Braund,male,22
2,"Cumings,female,38
3,"Heikkinen,female,26
4,"Futrelle,female,35

在本教程中,我們將學習如何使用 Pandas 處理 CSV 檔案,包括讀取和寫入 CSV 檔案,以及讀取 CSV 檔案的替代方法。

讀取 CSV 檔案

pandas.read_csv() 函式用於將 CSV 格式檔案讀取到 Pandas DataFrameTextFileReader 中。此函式接受 URL 或本地檔案路徑以將資料載入到 Pandas 環境中。

示例

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

import pandas as pd

# Import StringIO to load a file-like object for reading CSV
from io import StringIO

# Create string representing CSV data
data = """Name,Gender,Age
Braund,male,22
Cumings,female,38
Heikkinen,female,26
Futrelle,female,35"""

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

# read CSV into a Pandas DataFrame
df = pd.read_csv(obj)

print(df)

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

Name Gender Age
0 Braund male 22
1 Cumings female 38
2 Heikkinen female 26
3 Futrelle female 35

讀取 CSV 檔案的替代方法

除了pd.read_csv() 函式外,Pandas 還提供了一種讀取各種格式資料的替代方法,即pd.read_table() 函式。

pd.read_table() 函式用於將通用分隔檔案(如 CSV、TSV 或其他分隔符分隔格式)讀取到 Pandas DataFrame 中。它是載入 CSV 格式的最佳替代方案,並且此函式可以使用sep引數輕鬆處理各種分隔符。此外,此函式支援迭代或將檔案分成塊。

示例

此示例顯示了一種使用pd.read_table() 函式將 CSV 資料載入到 Pandas DataFrame 中的替代方法。在這裡,您需要使用sep引數指定分隔符以讀取逗號分隔值 (CSV)。

import pandas as pd
url ="blood_pressure.csv"

# read CSV into a Pandas DataFrame using the read_table() function
df = pd.read_table(url,sep=',')
print(df.head(5))

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

Patient Sex Age Group BP Before BP After
0 1 Male 30-45 143 153
1 2 Male 30-45 163 170
2 3 Male 30-45 153 168
3 4 Male 30-45 153 142
4 5 Male 30-45 146 141

寫入 CSV 檔案

Pandas 提供了一個名為pd.to_csv() 的函式,用於使用 Pandas 資料結構(如 DataFrame 或 Series 物件)建立或寫入 CSV 檔案。此函式允許您將資料匯出為 CSV 格式。

示例

這是一個演示如何使用pd.to_csv() 函式將 Pandas DataFrame 寫入 CSV 檔案的示例。

import pandas as pd

# dictionary of lists
d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],
'Date_of_purchase': ['2024-10-10', '2024-10-12', '2024-10-17', '2024-10-16', '2024-10-19', '2024-10-22']}

# creating dataframe from the above dictionary of lists
dataFrame = pd.DataFrame(d)
print("Original DataFrame:\n",dataFrame)

# write dataFrame to SalesRecords CSV file
dataFrame.to_csv("Output_written_CSV_File.csv")

# display the contents of the output csv
print("The output csv file written successfully and generated...")

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

Original DataFrame:
Car Date of Purchase
0 BMW 2024-10-10
1 Lexus 2024-10-12
2 Audi 2024-10-17
3 Mercedes 2024-10-16
4 Jaguar 2024-10-19
5 Bentley 2024-10-22
The output csv file written successfully and generated...

如果您在執行上述程式碼後訪問您的工作目錄,您將看到建立的名為Output_written_CSV_File.csv的 CSV 檔案。

廣告