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.