English

From 67.25s to 4.36s: Rewriting pandas Code with Polars

AI-translated

1We have suffered with pandas for a long time. Beyond its lack of multithreading and lazy execution, pandas also has problems such as memory amplification and index complexity.

Halfway through my O2O project, the time spent on feature engineering had already become unacceptable: it was comparable to the time spent running the model itself. I considered rewriting the code, but at that point I was unfamiliar with both pandas and Polars, while LLMs were clearly more familiar with pandas. To play it safe, I stuck with pandas. That decision left the project buried under more than 2,000 lines of Python and over 67 seconds of feature-engineering work. Right up to the deadline, I was still trying to improve test-set AUC through feature engineering, and I missed my last opportunity to refactor.

Once winter break began, I finally had time for a substantial overhaul. After a brief investigation, I decided to rewrite the project with Polars and abandon pandas entirely.

Figure 1: TPC-H benchmark

I chose Polars for three main reasons:

  • Speed. Polars is extremely fast and ranks among the fastest convenient-to-use libraries on PyPI, as shown in Figure 1. It provides optimizations such as multithreading, lazy execution, and memory management by default, increasing speed without imposing a substantial mental burden.
  • Cross-language support. pandas exposes a Python API, whereas Polars supports Node.js, Python, Rust, and R, among other languages. Their APIs are similar, making it easy to move between languages.
  • A convenient API. Polars has a rigorous, stable API. pandas emphasizes a highly flexible API, but that flexibility comes with inefficiency and considerable abstraction. Polars instead provides many built-in operations, avoiding Python functions unless they are necessary and delivering very high performance.

The Polars rewrite commit

Ironically, although the rewritten feature-engineering pipeline produced the same data overall, the row order was shuffled relative to the pandas output. That in turn changed the model’s results. Unfortunately, test-set AUC dropped, and even extensive brute-force hyperparameter tuning could not bring it back to its previous level.

  1. 1The title may be a little clickbaity.