Web制作、Web開発の歩き方

初心者のためのDjango入門

■第17話:PandasによるCSV、Excelデータの読み込みと書き出し

(最終更新日:2023.06.16)

Djangoフレームワークのイメージ
この記事は4分で読めます!
(絵が小さい場合はスマホを横に)

「Pandasを用いてデータを自在に操ろう!」

PandasはCSVやEXCELデータを読みこんで、DataFrameとして取り込むことができる。 反対にPandasで作成したDataFrameをCSVやEXCELデータに書き出すこともできる。 今回は、普段のドキュメント作成でも活用できるこれらの機能について説明する。


1.CSVとEXCELファイルの読み込み

まず、Pandasを用いてCSVファイルとEXCELファイルを読みこむ方法を説明する。 読みこみ方法は非常に簡単で、Pandasの関数を用いて、csvとexcel、それぞれを読みこむだけである。 これにより、DataFrameに各ファイルに書き込まれている内容が反映される。

CSV、EXCELファイルの読みこみ

CSV、EXCELファイルの読みこみ

1点気を付けたいのが、excelファイルの読み書きには、openpyxlが必要になる。 「pip install openpyxl」とコマンドを打ち、最初にopenpyxlをインストールしておこう。 実際、上記の命令で読みこんだDataFrameをprint(df_excel)を表示すると、以下のようになる。 (print(df_csv)も同じデータが表示される。) 前章の第3項で説明した方法と同様のデータフレームが作成されていることが分かる。

読みこんだDataFrameの表示

読み込み元のExcelの内容(上)、表示されたDataFrame(下)

2.データの書き出し

また、Pandasで作成したDataFrameをCSVやEXCELファイルに書き出すことができる。 以下に、DataFrameからCSVファイルとExcelファイルを作成する例を示す。 最初にDataFrameを作成し、それから、df.to_csvとdf.to_excelでCSVとEXCELファイルに出力している。

Seriesの作成

CSVとEXCELファイルへの出力

上記のコードを実行することで、出来たCSVとEXCELファイルが以下の通りとなる。 出力まで若干(2ファイルで10秒前後)時間が掛かるが、確かにCSVとEXCELファイルに出力することができた。

DataFrameの作成

CSV(左)とEXCEL(右)ファイルへの出力結果

3.まとめ

今回、CSV、ExcelデータをPandasで読み込むことができた。 PandasのDataFrameをCSV、Excelに書き出すこともできた。 非常に簡単なコードで、読み書きが出来ることが分かったと思う。

ExcelのマクロやVBでデータ処理を自動化したことがある人もいると思う。 PythonやPandasでは、同様の処理を更にシンプルに簡潔なコードで行うことができる。 他の強力なライブラリの力を借りて複雑なデータ処理を行うこともできる。 次章以降で説明するデータ操作やデータ分析と組み合わせて、有効活用してみよう。


▼参考図書、サイト

Pandas Seriesを徹底解説!  AI-interのPython3入門
Excelファイルを扱う上でのopenpyxlとpandas の違い  GAMMASOFT


Intro to Django for Beginners ■ Episode 17: Reading and Writing CSV and Excel Data with Pandas (Last updated: 2023.06.16) Image of the Django framework This article takes about 4 minutes to read! (Turn your phone sideways if the image looks small) "Master data manipulation using Pandas!" Pandas allows you to import CSV and Excel files and load them into a DataFrame. Likewise, you can export a DataFrame to CSV or Excel format. In this article, we’ll look at how these features can be useful in your everyday documentation tasks. [Table of Contents] Reading CSV and Excel Files Exporting Data Summary 1. Reading CSV and Excel Files Let’s begin by learning how to read CSV and Excel files using Pandas. It’s very simple — just use Pandas' built-in functions to read either file type. This will load the contents into a DataFrame, reflecting the structure of the source file. Reading CSV and Excel files Reading CSV and Excel files One important note: reading/writing Excel files requires the `openpyxl` library. Make sure to install it first using the command: pip install openpyxl. Once loaded, printing the DataFrame (e.g., print(df_excel)) will display its contents. You’ll see that the structure matches what was explained in section 3 of the previous chapter. Displaying the loaded DataFrame Original Excel data (top) and the displayed DataFrame (bottom) 2. Exporting Data You can also export a DataFrame created with Pandas to CSV or Excel format. The example below shows how to create a DataFrame and export it using df.to_csv and df.to_excel. Creating a Series Exporting to CSV and Excel files Running the code above will generate CSV and Excel files as shown below. Exporting takes about 10 seconds for both files, but you can confirm that the export completed successfully. Creating a DataFrame Export results: CSV (left), Excel (right) 3. Summary In this article, we learned how to read CSV and Excel data with Pandas. We also learned how to export a DataFrame to these formats. With just a few lines of code, you can easily handle file I/O operations. If you’ve previously automated tasks using Excel macros or VB, you’ll find that Python and Pandas provide a cleaner, more concise way to do the same. Pandas can also be combined with other powerful libraries for complex data processing. We encourage you to explore these tools in the upcoming chapters on data manipulation and analysis. ▼References   Pandas Series Explained in Detail! - AI-inter’s Python 3 Tutorial   Differences Between openpyxl and pandas for Excel Files - GAMMASOFT