第14章. pandas を使ったExcel ファイルの操作
この作品はAIを使って翻訳されている。ご意見、ご感想をお待ちしている:translation-feedback@oreilly.com
これまで、私たちは常にPythonとExcelを対話的な方法で扱ってきた。 Pythonスクリプトを実行してExcelを自動化し、Excelワークブックをユーザインタフェースとして、xlwingsまたはPython in Excelを介してPython関数を呼び出してきた。第VI部では、Excelアプリケーションを排除する。Excelで開くことなく、Excelファイルを直接扱うのだ。この章では、pandasを使ってExcelワークブックの読み取りと書き込みを行う方法を学ぶ。 まず、第8章のレポート作成のケーススタディを振り返ることから始める。その後、Excelファイルを扱うためにpandasが提供するツールについて、より詳しく紹介する。具体的には、読み取り用のread_excel関数とExcelFile、および書き込み用のto_excelメソッドとExcelWriterクラスだ。Excelアプリケーションではなくファイルを直接扱うため、この章のすべてのコードサンプルは、Linuxを含め、Pythonが動作する環境であればどこでも実行できる。
レポート作成のケーススタディ(第2弾)
第8章の「 」ケーススタディでは、pandasread_excel関数を使用して、付属リポジトリのsales_dataディレクトリにあるすべてのソースファイルを読み込んだ。今回のケーススタディでも同様の手順を踏む。ただし今回は、xlwingsを使用してレポートを所定のテンプレートに書き出す代わりに、pandasのみを使用し、DataFrameを新しいExcelファイルに書き出すことにする。 pandas単体ではExcelのグラフを作成できないため、このバージョンのレポートには表のみが含まれる。例14-1に示すPythonスクリプトsales_report_pandas.pyは、sales_report_xlwings.pyとほぼ同じに見える。違いは、スクリプトの最終行にあるDataFrameto_excelメソッドを介してレポートが生成される点だ。
例 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" ...
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