Python Pandas - 從 Excel 檔案讀取資料



Pandas 庫提供了強大的資料操作和分析工具。它提供的關鍵功能之一是能夠讀取和寫入 Excel 檔案中的資料。Pandas 提供了 **read_excel()** 方法來讀取 Excel 檔案並將資料載入到 Pandas DataFrame 中。該函式支援來自本地檔案系統或 URL 的 **xls** 和 **xlsx** 副檔名,並且需要 **xlrd** 和 **openpyxl** 包才能執行。

Pandas 中支援的 Excel 檔案格式

**pandas.read_excel()** 方法可以使用不同的模組讀取各種 Excel 檔案格式 -

  • **Excel 2007+ (.xlsx)** 檔案可以使用 **openpyxl** Python 模組讀取。

  • **Excel 2003 (.xls)** 檔案可以使用 **xlrd** 模組讀取。

  • **二進位制 Excel (.xlsb)** 檔案可以使用 **pyxlsb** 模組讀取。

  • 所有格式都可以使用 calamine 引擎讀取。

在本教程中,我們將學習如何使用 **pandas.read_excel()** 方法從 Excel 檔案讀取資料,涵蓋不同的場景,例如載入單個工作表、特定工作表和多個工作表。

在 Pandas 中讀取 Excel 檔案

**pandas.read_excel()** 方法用於讀取或載入 Excel 檔案到 Pandas DataFrame 中。此方法支援多種 Excel 檔案格式,例如 **.xls**、**.xlsx**、**.xlsm** 等,來自本地檔案系統或 URL。

注意:請確保您已在系統中安裝了所需的包(xlrd 和 openpyxl)。如果沒有,請使用以下命令安裝 -

pip install openpyxl 
pip install xlrd

示例

這是一個使用 **pd.read_excel()** 方法將本地系統 Excel 檔案讀取到 DataFrame 中的簡單示例,方法是指定檔案路徑。

import pandas as pd

# Read an Excel file
df = pd.read_excel('data.xlsx')

# Print the DataFrame
print('Output DataFrame:')
print(df)

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

Output DataFrame:
Sr.no Name Gender Age
0 1 Braund female 38
1 2 Cumings male 22
2 3 Heikkin female 35
3 4 Futrelle female 26

從 Excel 檔案讀取特定工作表

Excel 檔案可能包含多個具有不同名稱的工作表。要將特定工作表載入到 Pandas DataFrame 中,您可以將工作表名稱或索引指定到 **pd.read_excel()** 方法的 **sheet_name** 引數。

示例

以下是從 Excel 檔案中使用 **pd.read_excel()** 方法將特定工作表讀取到 Pandas DataFrame 中的示例。

import pandas as pd

# Read a specific sheet
df = pd.read_excel('data.xlsx', sheet_name="Sheet_2")

# Print the DataFrame
print('Output DataFrame:')
print(df)

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

Output DataFrame:
Name Value
0 string1 1
1 string2 3
2 Comment 5

將多個工作表讀取到 DataFrame 中

如果 Excel 檔案包含多個工作表,並且您需要將其中一些工作表讀取到 Pandas DataFrame 中,則可以透過將工作表名稱或索引列表傳遞到 **pd.read_excel()** 方法的 **sheet_name** 引數來實現。

示例

此示例使用 **pd.read_excel()** 方法將 Excel 檔案中的多個工作表讀取到 DataFrame 字典中。

import pandas as pd

# Read multiple sheets
df = pd.read_excel('data.xlsx', sheet_name=[0, 1])

# Print the DataFrame
print('Output Dict of DataFrames:')
print(df)

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

Output Dict of DataFrames:
{0:    Sr.no      Name  Gender  Age
0      1    Braund  female   38
1      2   Cumings    male   22
2      3   Heikkin  female   35
3      4  Futrelle  female   26, 1:       Name  Value
0  string1      1
1  string2      3
2  Comment      5}
廣告

© . All rights reserved.