第 14 章. 使用 pandas 操作Excel 文件
本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com
到目前为止,我们一直是以交互方式处理 Python 和 Excel 的。 我们运行 Python 脚本来自动化 Excel 操作,并将 Excel 工作簿作为用户界面来调用 Python 函数——无论是通过 xlwings 还是 Python in Excel。在第六部分中,我们将跳过 Excel 应用程序:我们将直接处理 Excel 文件,而无需在 Excel 中打开它们。在本章中,您将学习如何使用 pandas 读写 Excel 工作簿。 我们将首先回顾第 8 章中的报表案例研究。随后,我将更深入地介绍 pandas 用于处理 Excel 文件的工具:用于读取的read_excel函数和ExcelFile类,以及用于写入 Excel 文件的to_excel方法和ExcelWriter类。由于我们处理的是文件而非 Excel 应用程序,本章中的所有代码示例在 Python 运行的任何环境中均可运行,包括 Linux。
报表案例研究(第二版)
在第8章的 案例研究中,我们使用pandasread_excel函数读取了配套代码库中sales_data目录下的所有源文件。在本版本的案例研究中,我们将采用相同的方法。不过,这次我们将不再使用xlwings将报告写入预格式化的模板,而是继续使用pandas,将DataFrame写入一个新的Excel文件。 由于 pandas 本身无法创建 Excel 图表,因此本版本的报告将仅包含表格。如示例 14-1 所示,Python 脚本sales_report_pandas.py 与sales_report_xlwings.py 几乎完全相同。区别在于,报告是通过脚本最后一行中的to_excelDataFrame 方法生成的。
示例 14-1. sales_report_pandas .py
frompathlibimportPathimportpandasaspd# Directory of this filethis_dir=Path(__file__).resolve().parent# Read in all filesparts=[]forpathin(this_dir/"sales_data").rglob("*.xls*"):(f"Reading{path.name}")part=pd.read_excel(path,engine="calamine")parts.append(part)# Combine the DataFrames from each file into a single DataFramedf=pd.concat(parts)# Pivot each store into a column and sum up all transactions per datepivot=pd.pivot_table(df,index="transaction_date",columns="store",values="amount",aggfunc="sum")# Resample to end of month and assign an index namesummary=pivot.resample("ME" ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access