Web制作、Web開発の歩き方

初心者のためのDjango入門

■第20話:Rust製で高速!Polarsによるデータ集計と分析

(最終更新日:2023.06.26)

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

「Pandasデータを可視化しよう!」

Polarsは、PythonとRustで書かれた高速なDataFrameライブラリだ。 Pandasと同様に、データの操作と分析を容易にするための多くの機能を提供しており、機能としては類似している。 ただし、Pandasとは異なり内部の処理をRustで行うことにより、大量のデータを扱う際のパフォーマンスの向上やメモリ効率の改善に重点を置いている。 今回は、そんなPythonライブラリ、Polarsについて紹介する。


1.Polarsのインストール

仮想環境の設定やPython自体のインストールに関しては16話で説明した内容を見てほしい。 Pythonが使える環境で、「pip install polars」を行う。これだけで、Polarsを使うことができる。簡単である。

1点注意としては、excelやcsvファイルの読み込み、書き出しにはpandasとは別のライブラリが必要になる。 「pip install xlsx2csv」とコマンドを打って、インストールしよう。これで、Pandasとほぼ同様に、excelやcsvファイルの読み書きができるはずだ。

excelデータの読み込み

excelデータの読み込み(上)とその出力結果(下)

2.Polarsの基本的なデータ構造

Polarsは、データを操作するための2つの主要なデータ構造、SeriesとDataFrameを提供する。 これは、Pandasと全く一緒である。 念のため再度説明すると、Seriesは1次元の配列で、同じデータ型のデータを保持する。 一方、DataFrameは2次元のテーブルで、異なるデータ型のデータを保持することができる。 以下に、SeriesとDataFrameの作成例を示す。 Seriesを作成すると、その形状である(5, 1)(1は省略される)が表示され、1~5が格納されている様子が出される。

seriesの作成

seriesの作成(上)とその出力結果(下)

DataFrameを出力すると、その形状である(5, 2)が表示され、1~5とA~Eが格納されている様子が出される。 また、それぞれの項目(idとclass)の型がi64(64bit整数型)、str(文字列型)という表記で示される。

データフレームの作成

データフレームの作成(上)とその出力結果(下)

3.Pandasとの比較

■パフォーマンスとメモリ効率
Polarsは、大量のデータを扱う際のパフォーマンスの向上とメモリ効率の改善に重点を置いている。 これは、PolarsがRustで書かれているため、メモリ管理と並列処理がより効率的に行われる。 一方、PandasはPythonで書かれており、大量のデータを扱う際にはパフォーマンスやメモリ効率の問題が生じることがある。

■並列処理
Polarsはマルチスレッドの操作をサポートしており、大量のデータを高速に処理することが可能だ。 一方、Pandasは主に単一スレッドで動作し、大量のデータの処理には時間がかかることがある。

■APIの違い
PolarsとPandasのAPIは似ていますが、完全に同じではない。一部の操作は、両者の間で異なる関数やパラメータを使用することがある。 したがって、PandasからPolarsに移行する際には、APIの違いに注意する必要があります。 例えば、データフレームの列を選択する方法は、PandasとPolarsで少し異なります。 Pandasは「df_pandas["A"]」とするのに対して、Polarsは「df_polars.select("A")」と書く。 このように、メソッドの呼び出し方が異なるので、 分からなくなったら公式サイトで使い方を確認しよう。

■データ型のサポート
Pandasは、Pythonの基本的なデータ型に加えて、カテゴリ型や日付/時間型などの特殊なデータ型をサポートしている。 一方、Polarsはこれらの特殊なデータ型をサポートしていますが、その実装はPandasとは異なる場合がある。

■エコシステムとコミュニティ
Pandasは、Pythonのデータ分析エコシステムの中心的な部分を占めており、 多くのライブラリ(例えば、Matplotlib、Seaborn、Scikit-learnなど)との統合が深い。 また、Pandasは広範なコミュニティサポートと豊富なドキュメンテーションを持っている。

一方、Polarsは比較的新しいライブラリで、そのエコシステムとコミュニティはまだ発展途上だ。 しかし、そのパフォーマンスと効率性は、大規模なデータセットを扱う必要があるデータサイエンティストやエンジニアにとって魅力的である。

4.まとめ

Polarsは大量のデータを効率的に処理したり、データ変換するのが得意である。 ただし、Pandasとは若干命令や必要なライブラリが異なるというところが注意点だ。 加えて、新しいライブラリであるが故、 Matplotlib、Seaborn、Scikit-learnなどの有名なライブラリとの連携に関しても今は注意が必要である。

これらの点を踏まえた上で、ハイパフォーマンスなPythonライブラリ、Polarsをぜひ活用してみよう。


▼参考図書、サイト

Rust製高速データフレームライブラリ、Polarsを試す  Python Monthly Topics
pandasから移行する人向け polars使用ガイド  qiita


Django Tutorial for Beginners ■Episode 20: Fast with Rust! Data Aggregation and Analysis with Polars (Last updated: 2023.06.26) Image of Django Framework This article takes 6 minutes to read! (Rotate your phone horizontally if the image appears too small) "Visualize your Pandas data!" Polars is a fast DataFrame library written in Python and Rust. Similar to Pandas, it provides a wide range of features for easy data manipulation and analysis. However, unlike Pandas, its core processing is done in Rust, enabling better performance and memory efficiency when handling large datasets. This article introduces Polars, a powerful Python library for data handling. [Table of Contents] Installing Polars Basic Data Structures in Polars Comparison with Pandas Summary 1. Installing Polars For Python and virtual environment setup, please refer to Episode 16. If Python is already available, simply run pip install polars to install Polars. That's all it takes—it's simple. Note: To read and write Excel or CSV files, you'll need additional libraries different from Pandas. Run pip install xlsx2csv to enable similar file operations. Reading Excel data Reading Excel data (top) and output result (bottom) 2. Basic Data Structures in Polars Polars provides two main data structures for handling data: Series and DataFrame— just like Pandas. To recap: a Series is a one-dimensional array with uniform data types, while a DataFrame is a two-dimensional table that can contain different data types. Below is an example of how to create a Series and a DataFrame. When creating a Series, you'll see its shape as (5, 1) (1 is often omitted), showing the values 1 to 5. Creating a Series Creating a Series (top) and output result (bottom) When outputting a DataFrame, its shape (5, 2) is shown along with the stored values (1–5 and A–E). The data types for each column (e.g., id as i64 and class as str) are also displayed. Creating a DataFrame Creating a DataFrame (top) and output result (bottom) 3. Comparison with Pandas ■ Performance and Memory Efficiency Polars focuses on improving performance and memory efficiency when handling large datasets. Since it's written in Rust, it provides more efficient memory management and parallel processing. Pandas, on the other hand, is written in Python and may struggle with performance or memory usage for large data volumes. ■ Parallel Processing Polars supports multithreaded operations, allowing for fast processing of large data. Pandas mainly runs in a single thread, which can be slower for big datasets. ■ API Differences The APIs of Polars and Pandas are similar but not identical. Some operations use different functions or parameters. For example, selecting a column in Pandas is done with df_pandas["A"], while in Polars it’s written as df_polars.select("A"). Be sure to check the official documentation if you’re unsure. ■ Data Type Support Pandas supports specialized data types like categories and datetime. Polars also supports these types, though the implementations may differ. ■ Ecosystem and Community Pandas is at the center of the Python data analysis ecosystem, with deep integrations with libraries like Matplotlib, Seaborn, and Scikit-learn. It has a large community and extensive documentation. In contrast, Polars is a newer library, and its ecosystem and community are still developing. However, its performance and efficiency make it attractive for data scientists and engineers handling large datasets. 4. Summary Polars excels at efficiently processing and transforming large datasets. However, it uses slightly different syntax and requires different supporting libraries compared to Pandas. Being a relatively new library, caution is needed when integrating with other popular tools like Matplotlib, Seaborn, and Scikit-learn. With these considerations in mind, Polars is a high-performance Python library worth exploring. ▼References   Exploring Polars, a High-Speed DataFrame Library in Rust – Python Monthly Topics   Polars Usage Guide for Those Migrating from Pandas – Qiita