![Revisit consent button](../images/body-df29beacd7496220cc94.svg)
We value your privacy
We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies.
Customise Reject All Accept All
Customise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)
We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.
The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more
NecessaryAlways Active
Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.
  * Cookie
BCTempID
  * Duration
10 minutes
  * Description
No description available.


  * Cookie
__cf_bm
  * Duration
1 hour
  * Description
This cookie, set by Cloudflare, is used to support Cloudflare Bot Management. 


  * Cookie
AWSALBCORS
  * Duration
7 days
  * Description
Amazon Web Services set this cookie for load balancing.


  * Cookie
_cfuvid
  * Duration
session
  * Description
Cloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services


  * Cookie
li_gc
  * Duration
6 months
  * Description
Linkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.


  * Cookie
__hssrc
  * Duration
session
  * Description
This cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.


  * Cookie
__hssc
  * Duration
1 hour
  * Description
HubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.


  * Cookie
wpEmojiSettingsSupports
  * Duration
session
  * Description
WordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.


  * Cookie
BCSessionID
  * Duration
1 year 1 month 4 days
  * Description
Blueconic sets this cookie as a unique identifier for the BlueConic profile.


  * Cookie
_octo
  * Duration
1 year
  * Description
No description available.


  * Cookie
logged_in
  * Duration
1 year
  * Description
No description available.


  * Cookie
__Secure-YEC
  * Duration
past
  * Description
YouTube sets this cookie to stores the user's video player preferences using embedded YouTube video


  * Cookie
__eoi
  * Duration
6 months
  * Description
Description is currently not available.


  * Cookie
AWSALBTGCORS
  * Duration
7 days
  * Description
No description available.


  * Cookie
login-status-p
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
AWSALBTG
  * Duration
7 days
  * Description
No description available.


  * Cookie
csrf_token
  * Duration
session
  * Description
No description available.


  * Cookie
token_v2
  * Duration
1 day
  * Description
Description is currently not available.


  * Cookie
D
  * Duration
1 year
  * Description
Description is currently not available.


  * Cookie
PHPSESSID
  * Duration
session
  * Description
This cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.


  * Cookie
VISITOR_PRIVACY_METADATA
  * Duration
6 months
  * Description
YouTube sets this cookie to store the user's cookie consent state for the current domain. 


  * Cookie
cookietest
  * Duration
session
  * Description
The cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.


  * Cookie
__Host-airtable-session
  * Duration
1 year
  * Description
This cookie is used to enable us to integrate the services of Airtable.


  * Cookie
__Host-airtable-session.sig
  * Duration
1 year
  * Description
This cookie is used to enable us to integrate the services of Airtable.


  * Cookie
m
  * Duration
1 year 1 month 4 days
  * Description
Stripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.


  * Cookie
BIGipServer*
  * Duration
session
  * Description
Marketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. 


  * Cookie
__cfruid
  * Duration
session
  * Description
Cloudflare sets this cookie to identify trusted web traffic.


  * Cookie
_GRECAPTCHA
  * Duration
6 months
  * Description
Google Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.


  * Cookie
__Secure-YNID
  * Duration
6 months
  * Description
Google cookie used to protect user security and prevent fraud, especially during the login process.


  * Cookie
cookieyes-consent
  * Duration
1 year
  * Description
CookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.


Functional
Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.
  * Cookie
lidc
  * Duration
1 day
  * Description
LinkedIn sets the lidc cookie to facilitate data center selection.


  * Cookie
brw
  * Duration
1 year
  * Description
No description available.


  * Cookie
brwConsent
  * Duration
5 minutes
  * Description
Description is currently not available.


  * Cookie
WMF-Uniq
  * Duration
1 year
  * Description
Description is currently not available.


  * Cookie
loom_anon_comment
  * Duration
1 year
  * Description
No description available.


  * Cookie
loom_referral_video
  * Duration
session
  * Description
Description is currently not available.


  * Cookie
VISITOR_INFO1_LIVE
  * Duration
6 months
  * Description
A cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.


  * Cookie
yt-remote-connected-devices
  * Duration
Never Expires
  * Description
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.


  * Cookie
ytidb::LAST_RESULT_ENTRY_KEY
  * Duration
Never Expires
  * Description
The cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.


  * Cookie
yt-remote-device-id
  * Duration
Never Expires
  * Description
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.


  * Cookie
yt-remote-session-name
  * Duration
session
  * Description
The yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.


  * Cookie
yt-remote-fast-check-period
  * Duration
session
  * Description
The yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.


  * Cookie
yt-remote-session-app
  * Duration
session
  * Description
The yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.


  * Cookie
yt-remote-cast-available
  * Duration
session
  * Description
The yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.


  * Cookie
yt-remote-cast-installed
  * Duration
session
  * Description
The yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.


  * Cookie
cp_session
  * Duration
3 months
  * Description
Codepen sets this cookie for Help systems found in the website.


  * Cookie
loid
  * Duration
1 year 1 month 4 days
  * Description
This cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.


Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.
  * Cookie
__hstc
  * Duration
6 months
  * Description
Hubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).


  * Cookie
hubspotutk
  * Duration
6 months
  * Description
HubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.


  * Cookie
_ga
  * Duration
1 year 1 month 4 days
  * Description
Google Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.


  * Cookie
_ga_*
  * Duration
1 year 1 month 4 days
  * Description
Google Analytics sets this cookie to store and count page views.


  * Cookie
__Host-psifi.analyticsTrace
  * Duration
6 hours
  * Description
Description is currently not available.


  * Cookie
__Host-psifi.analyticsTraceV2
  * Duration
6 hours
  * Description
Description is currently not available.


  * Cookie
_gh_sess
  * Duration
session
  * Description
GitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.


  * Cookie
YSC
  * Duration
session
  * Description
YSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.


  * Cookie
ajs_anonymous_id
  * Duration
1 year
  * Description
This cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.


  * Cookie
vuid
  * Duration
1 year 1 month 4 days
  * Description
Vimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. 


Performance
Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.
  * Cookie
AWSALB
  * Duration
7 days
  * Description
AWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.


  * Cookie
acq
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
acq.sig
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
ptc
  * Duration
2 years
  * Description
No description available.


Advertisement
Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.
  * Cookie
muc_ads
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to collect user behaviour and interaction data to optimize the website.


  * Cookie
guest_id_marketing
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor.


  * Cookie
guest_id_ads
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor.


  * Cookie
personalization_id
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.


  * Cookie
guest_id
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.


  * Cookie
bcookie
  * Duration
1 year
  * Description
LinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.


  * Cookie
__Secure-ROLLOUT_TOKEN
  * Duration
6 months
  * Description
YouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.


  * Cookie
yt.innertube::nextId
  * Duration
Never Expires
  * Description
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.


  * Cookie
yt.innertube::requests
  * Duration
Never Expires
  * Description
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.


  * Cookie
session_tracker
  * Duration
session
  * Description
This cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.


  * Cookie
edgebucket
  * Duration
session
  * Description
Reddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.


  * Cookie
did
  * Duration
1 year
  * Description
Arbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.


Uncategorised
Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet.
No cookies to display.
Reject All Save My Preferences Accept All
Toggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation
[](https://towardsdatascience.com/)
Publish AI, ML & data-science insights to a global community of data professionals.
Sign in[Submit an Article](https://write.insightmediagroup.io)
[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)
* * *
[Write For TDS](https://towardsdatascience.com/submissions/)
[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search
[Data Science](https://towardsdatascience.com/category/data-science/)
# I Rewrote a Real Data Workflow in Polars. Pandas Didn’t Stand a Chance.
From 61 seconds to 0.20 seconds — and the mental model shift I didn't expect
[Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)
May 7, 202614 min read
![](../images/000.jpg)
Created with Gemini AI
I'll be honest — I wasn't actively looking for Polars.
I've been on a bit of a Pandas optimization journey lately. First, I wrote about why you should [stop writing loops in Pandas](https://towardsdatascience.com/stop-writing-loops-in-pandas-do-this-instead/) and think in columns instead.
Then I went deeper to profiling real workflows, fixing vectorization mistakes, and ended up cutting a [61-second pipeline down to 0.33 seconds](https://towardsdatascience.com/i-reduced-my-pandas-runtime-by-95-heres-what-i-was-doing-wrong/) using nothing but better Pandas and NumPy. That one surprised even me.
So I was in a good place with Pandas. I felt like I finally understood how to use it properly.
Then someone dropped a comment on one of my posts. Something along the lines of: _"Have you tried Polars? It's built for exactly this kind of thing."_
I'd seen the name floating around in the data community. There was buzz around it — something about speed, about a completely different way of thinking about data pipelines. But I'd never actually touched it.
That comment was enough to push me over the edge.
So I did what I always do. I got curious, I installed it, and I rewrote the exact same workflow from my last article, the one I'd already optimized in Pandas, in a tool I'd never used before.
What I found surprised me. Not just the speed numbers, but what Polars quietly teaches you about how data pipelines actually work.
Learn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) roadmap.
## **Isn't Pandas Enough?**
Fair question.
In my last article, I took a slow Pandas pipeline and optimized it down to 0.33 seconds. Vectorized operations, correct data types, no unnecessary copies. The results were honestly better than I expected.
So why are we even talking about Polars?
Here's the thing. Everything I did in that article was me doing the optimization manually. I had to know which operations were slow, why they were slow, and how to fix them. Polars does a lot of that thinking for you automatically, before it even runs your code.
On top of that, Polars is built on a completely different foundation than Pandas. It uses all your CPU cores by default. It manages memory differently. And it introduces a way of writing data pipelines that, once it clicks, changes how you think about the whole process.
Optimized Pandas is impressive. But it still has a ceiling. This article is about what's on the other side of it.
## **The Workflow**
To keep things consistent and useful for anyone who followed along with my last article. I'm using the same synthetic e-commerce dataset. One million rows. Nothing exotic. Just the kind of data you'd realistically encounter in the wild.
If you want to generate it yourself, here's the setup code:
python

```
import pandas as pd
import numpy as np
import time

np.random.seed(42)

n = 1_000_000

regions = ['north', 'south', 'east', 'west']
categories = ['electronics', 'clothing', 'furniture', 'food', 'sports']
statuses = ['completed', 'returned', 'pending', 'cancelled']

df = pd.DataFrame({
    'order_id': np.arange(1000, 1000 + n),
    'order_date': pd.date_range(start='2022-01-01', periods=n, freq='1min'),
    'region': np.random.choice(regions, size=n),
    'category': np.random.choice(categories, size=n),
    'sales': np.random.randint(100, 10000, size=n),
    'quantity': np.random.randint(1, 20, size=n),
    'discount': np.round(np.random.uniform(0.0, 0.5, size=n), 2),
    'status': np.random.choice(statuses, size=n),
})

df.to_csv('large_sales_data.csv', index=False)
```

The pipeline we're running on it is straightforward. The kind of thing that shows up in real workflows all the time:
  * Fix data types upfront
  * Calculate net revenue per order
  * Flag high-value orders
  * Aggregate total net revenue by region


Simple. Familiar. And already optimized in Pandas from the last article, which makes it the perfect benchmark for Polars.
## **The Pandas Version**
I'm not going to show you the naive Pandas code here. I already did that in my last article — the version with three `.apply()` calls that took 61 seconds on this same dataset. If you haven't read that one, it's worth a look.
What I'm showing here is the optimized version. The best Pandas can do on this pipeline.
python

```
import pandas as pd
import numpy as np
import time

df = pd.read_csv('large_sales_data.csv')

start = time.time()

# Fix data types upfront
df['region'] = df['region'].astype('category')
df['category'] = df['category'].astype('category')
df['status'] = df['status'].astype('category')

# Vectorized revenue calculation
df['net_revenue'] = df['sales'] * df['quantity'] * (1 - 0.075)

# Vectorized flagging
df['order_flag'] = np.where(df['net_revenue'] > 50000, 'high', 'low')

# Aggregation
result = df.groupby('region')['net_revenue'].sum()

end = time.time()
print(f"Pandas runtime: {end - start:.2f} seconds")
print(result)
```

This is clean Pandas. Vectorized operations, correct data types, no unnecessary intermediate columns. Everything I learned from going down that rabbit hole.
And the result?
text

```
Pandas runtime: 0.31 seconds
```

That's already really good. Genuinely impressive for a million rows.  
But here's the question I kept sitting with after seeing that number: what does it look like when the tool is doing the optimization for you, instead of you doing it manually?
That's what we're about to find out.
## **Installing Polars and First Impressions**
Getting started was straightforward. If you're on Google Colab like me, one line is all you need:
python

```
!pip install polars 
import polars as pl 
print(pl.__version__)
```

text

```
1.35.2
```

Done. No environment headaches, no dependency conflicts. That alone was a good start.
But then I opened the Polars documentation and immediately noticed something. The syntax looked familiar enough — DataFrames, columns, filtering — but the way you're supposed to _think_ about operations felt different. 
In Pandas, you work with your data step by step. You do something, store the result, do something else. In Polars, you describe what you want as a single expression, and Polars figures out how to execute it.
I didn't fully understand that yet. But I was about to.
The other thing that caught my eye immediately was this concept of **lazy** vs **eager** execution. In Pandas, every line of code runs the moment you write it. Polars gives you a choice: you can run eagerly like Pandas, or you can build up a full query plan first and let Polars optimize it before executing anything.
I didn't know what that meant in practice yet. But I kept seeing it everywhere in the docs. So I decided the best way to understand it was to just rewrite my pipeline and see what happened.
## **The Eager Version**
python

```
import polars as pl
import time

start = time.time()

result = (
    pl.read_csv('large_sales_data.csv')
    .with_columns([
        (pl.col('sales') * pl.col('quantity') * (1 - 0.075)).alias('net_revenue')
    ])
    .with_columns([
        pl.when(pl.col('net_revenue') > 50000)
        .then(pl.lit('high'))
        .otherwise(pl.lit('low'))
        .alias('order_flag')
    ])
    .group_by('region')
    .agg(pl.col('net_revenue').sum())
)

end = time.time()
print(f"Polars Eager runtime: {end - start:.2f} seconds")
print(result)
```

text

```
Polars Eager runtime: 0.83 seconds
```

The first thing I noticed was the method chaining. In Pandas, I was making separate assignments, doing one thing, storing the result, doing the next thing.
Here, everything flows as a single expression from start to finish. You're describing the entire pipeline at once.
Let me break down the syntax quickly since some of it will look unfamiliar:
  * `pl.read_csv()` — reads the CSV, same concept as `pd.read_csv()`. Nothing surprising.
  * `.with_columns([...])` — this is how Polars adds or transforms columns. The equivalent of `df['new_col'] = ...` in Pandas. You can compute multiple columns in a single call.
  * `pl.col('sales')` — this is how you reference a column in Polars. Instead of `df['sales']`, you write `pl.col('sales')`. You're not grabbing the data directly — you're describing an operation on that column. That distinction matters more than it sounds.
  * `.alias('net_revenue')` — just naming the result. Like saying "call this new column net_revenue."
  * `pl.when(...).then(...).otherwise(...)` — Polars' version of `np.where()`. Reads almost like plain English: when this condition is true, return this value, otherwise return that one.
  * `.group_by('region').agg(...)` — same concept as Pandas `.groupby()`. Group the data, then define your aggregation. Different syntax, same idea.


Now here's the thing. That eager version ran in 0.83 seconds. That's actually slower than our optimized Pandas at 0.31 seconds. If I'd stopped here, I'd have written Polars off entirely.
But I kept reading the docs. And I found something called lazy evaluation.
## **The Lazy Version**
python

```
start = time.time()

result = (
    pl.scan_csv('large_sales_data.csv')
    .with_columns([
        (pl.col('sales') * pl.col('quantity') * (1 - 0.075)).alias('net_revenue')
    ])
    .with_columns([
        pl.when(pl.col('net_revenue') > 50000)
        .then(pl.lit('high'))
        .otherwise(pl.lit('low'))
        .alias('order_flag')
    ])
    .group_by('region')
    .agg(pl.col('net_revenue').sum())
    .collect()
)

end = time.time()
print(f"Polars Lazy runtime: {end - start:.2f} seconds")
print(result)
```

text

```
Polars Lazy runtime: 0.20 seconds
```

Spot the two differences from the eager version. `pl.read_csv()` became `pl.scan_csv()` — this tells Polars not to load anything yet, just start building a query plan. And `.collect()` was added at the end — that's where you tell Polars "okay, now execute everything."
Two changes. That's it.
And just like that, 0.83 seconds became 0.20 seconds.
Polars lazy is 35% faster than our already optimized Pandas pipeline. Without me doing any manual optimization. Without me profiling anything. Without me knowing in advance which operations were bottlenecks.
Polars figured that out on its own.
That's when I started paying attention.
## **Mental Model Shift #1 — Lazy vs Eager Execution**
This is the one that changed how I think about data pipelines.  
In Pandas, every line of code executes the moment you write it. You assign a column — it runs. You filter a DataFrame — it runs. You group and aggregate — it runs. 
Each operation is independent, immediate, and unaware of what comes before or after it.
That's eager execution. It's intuitive. It feels natural because it matches how we think about writing code step by step.
Polars gives you a choice.
When you use `pl.scan_csv()` instead of `pl.read_csv()`, you're telling Polars: _don't execute anything yet._ Just start building a plan. Every `.with_columns()`, every `.filter()`, every `.group_by()` you chain after that isn't running — it's being recorded. You're describing what you want, not triggering it.
Then when you call `.collect()` at the end, Polars takes that entire plan, looks at it as a whole, optimizes it, and then executes it in one efficient pass.
Think of it this way:
  * **Pandas** is like following a recipe step by step. Chop the onions. Put them in the pan. Add the garlic. Each instruction happens immediately, in order, one at a time.
  * **Polars lazy** is like a chef who reads the entire recipe first, figures out the most efficient way to prepare everything, and then executes it in the optimal order. Same result. Less wasted effort.


That optimization step is the key. Before Polars runs a single line of your pipeline it asks: what columns do we actually need? What rows can we eliminate early? What operations can be parallelized? What work can be skipped entirely?
You can actually see the query plan Polars builds before it executes.
Run this:
python

```
lazy_query = (
    pl.scan_csv('large_sales_data.csv')
    .with_columns([
        (pl.col('sales') * pl.col('quantity') * (1 - 0.075)).alias('net_revenue')
    ])
    .with_columns([
        pl.when(pl.col('net_revenue') > 50000)
        .then(pl.lit('high'))
        .otherwise(pl.lit('low'))
        .alias('order_flag')
    ])
    .group_by('region')
    .agg(pl.col('net_revenue').sum())
)

print(lazy_query.explain())
```

That `.explain()` call shows you exactly what Polars is planning to do before it does it. It's the optimizer's thinking made visible.  
This is something Pandas simply doesn't have. 
In Pandas, the optimization is your responsibility. You have to know which operations are expensive, profile your code, and restructure it manually — which is exactly what I did in my last article. In Polars lazy mode, the optimizer handles that for you.
That's not a small difference. That's a fundamentally different relationship between you and your data pipeline.
## **Mental Model Shift #2 — Query Optimization**
Once I understood lazy evaluation, I started wondering — okay, but what exactly is Polars optimizing? What is it actually doing differently under the hood?
Turns out there are two big ones worth knowing about. And once you understand them, you start seeing why Polars is faster not just on this pipeline, but on almost any non-trivial workflow.
### **Predicate Pushdown**
Let's say you add a filter to our pipeline — you only want completed orders:
python

```
result = (
    pl.scan_csv('large_sales_data.csv')
    .with_columns([
        (pl.col('sales') * pl.col('quantity') * (1 - 0.075)).alias('net_revenue')
    ])
    .filter(pl.col('status') == 'completed')
    .group_by('region')
    .agg(pl.col('net_revenue').sum())
    .collect()
)
```

In eager mode — Pandas or Polars eager — this is what happens: load all one million rows, compute net revenue for all of them, then filter down to completed orders. You did expensive work on rows you were going to throw away anyway.
Polars lazy does something smarter. It looks at the entire query plan and says: there's a filter here. Let me apply that filter as early as possible — ideally before loading data, or right after. That way I'm only doing the expensive computations on the rows that actually matter.
That's predicate pushdown. Push the filter down to the earliest possible point in the pipeline. Less data processed. Less memory used. Faster result.
### **Projection Pruning**
Same idea, but for columns instead of rows.
Our CSV has eight columns. But our final result only needs `sales`, `quantity`, `region`, and `status`. Polars looks at the query plan, figures out which columns are actually needed to produce the final output, and only loads those. The rest are ignored entirely.
In Pandas, you load everything first and figure out what you need later. Polars figures out what it needs before loading anything.  
These two optimizations — predicate pushdown and projection pruning — are what a database query optimizer does. If you've ever written SQL and wondered why the database is fast even on massive tables, this is a big part of why.
And that's the mental shift here. When you write a Polars lazy pipeline, you're not really writing a script anymore. You're writing a query. You're describing what you want, and Polars — like a database engine — figures out the most efficient way to get it.
That's a different way of thinking. And once it clicks, you start approaching data pipelines differently. Instead of asking "what should I do next?", you start asking "what do I actually need at the end?" and working backwards from there.
## **Mental Model Shift #3 — Columnar Memory**
There's one more piece to why Polars is fast. And it lives at a level below your code.
Pandas stores data in a row-oriented format under the hood. Imagine a spreadsheet where each row is stored together in memory — all the values for order 1, then all the values for order 2, and so on. That works fine for looking up individual records. 
But when you want to compute something across an entire column — like summing all revenue values — Pandas has to hop through memory, picking out the relevant value from each row one at a time.
Polars uses a columnar memory format called Apache Arrow. Instead of storing rows together, it stores columns together. All the revenue values sit next to each other in memory. All the region values sit next to each other. When you need to compute something on a column, everything you need is already in one contiguous block of memory.
Why does that matter? Two reasons.
First, modern CPUs are built to process contiguous blocks of memory extremely efficiently. When your data is laid out in columns, the CPU can tear through it using vectorized instructions — processing multiple values in a single operation. Row-oriented storage breaks that optimization.
Second, columnar storage means Polars only touches the columns it needs. If your DataFrame has 20 columns but your operation only needs 3, Polars works with those 3 columns in memory. Pandas loads the whole thing regardless.
You don't have to do anything to get this benefit. It's just how Polars is built.
Think of it this way. Pandas is like a filing cabinet where each drawer contains everything about one customer — their name, their orders, their payment history, all together. 
Polars is like a filing cabinet where one drawer has all the names, another has all the orders, another has all the payment histories. If you need to analyze payment histories across all customers, Polars opens one drawer. Pandas opens every single one.
That's the columnar memory model. And combined with lazy evaluation and query optimization, it's why Polars can do in 0.20 seconds what takes Pandas 0.31 seconds — even after Pandas has been carefully optimized by hand.
## **Where Pandas Still Wins**
I want to be straight with you here. This article isn't a Pandas obituary.
After going through this entire exercise, there are still situations where I'd reach for Pandas without hesitation.
For quick exploration and ad hoc analysis, Pandas is hard to beat. The syntax is familiar, the ecosystem is massive, and when you're just poking around a dataset trying to understand it, the performance difference doesn't matter. You're not running a pipeline — you're thinking out loud.
For small datasets, Polars' advantages largely disappear. The overhead of building a query plan only pays off when there's enough data to make optimization worthwhile. On a few thousand rows, just use Pandas.
For visualization and integrations, Pandas is deeply woven into the Python data ecosystem. Matplotlib, Seaborn, Scikit-learn, Statsmodels — they all speak Pandas natively. Polars is catching up, but Pandas is still the common language.
And honestly, for teams and collaborators, familiarity matters. If everyone on your team knows Pandas and nobody knows Polars, introducing it has a real cost.
I'm not replacing Pandas. I'm becoming more intentional about when I use it.
Small dataset, quick exploration, visualization, team familiarity — Pandas. Large dataset, repeated pipeline, production workflow, performance matters — Polars.
Both tools. Right situations.
## **Conclusion**
Here's what I came in expecting: a speed comparison. Run the same code in two libraries, show the numbers, done.
Here's what I actually got: a different way of thinking about data.
The speed numbers are real — we went from a 61-second broken Pandas pipeline in my last article, to 0.31 seconds with optimized Pandas, to 0.20 seconds with Polars lazy evaluation. That's a journey worth documenting.
But the more lasting thing is what Polars quietly teaches you along the way. That filters should be applied as early as possible. That you should only load what you need. That describing what you want and letting an optimizer figure out the how is a legitimate — and powerful — way to write data pipelines.
Those aren't just Polars ideas. They're good data engineering ideas. And I wouldn't have sat down to really understand them if a comment on one of my posts hadn't pushed me toward a tool I'd never used before.
Pandas didn't become worse through any of this. My expectations just got bigger.
If you've got a workflow that feels slower than it should — even after you've cleaned up the code — it might be worth asking whether the tool itself has a ceiling. Sometimes the next step isn't writing better code. It's writing the same code in something built differently.
What workflows are you running that might be worth a rewrite?
## Register Now to Continue Reading
### Unlock Towards Data Science with a Free Account
All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.
Register for freeSign in to your account
* * *
![](../images/body-542334df68a32cd56c4a.jpeg)
Written By
## [Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)
[See all from Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)
[Data Science](https://towardsdatascience.com/tag/data-science/)[Pandas](https://towardsdatascience.com/tag/pandas/)[Polars](https://towardsdatascience.com/tag/polars/)[Programming](https://towardsdatascience.com/tag/programming/)[Python](https://towardsdatascience.com/tag/python/)
Share This Article
  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fi-rewrote-a-real-data-workflow-in-polars-pandas-didnt-stand-a-chance%2F&title=I%20Rewrote%20a%20Real%20Data%20Workflow%20in%20Polars.%20Pandas%20Didn%E2%80%99t%20Stand%20a%20Chance.)
  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fi-rewrote-a-real-data-workflow-in-polars-pandas-didnt-stand-a-chance%2F&title=I%20Rewrote%20a%20Real%20Data%20Workflow%20in%20Polars.%20Pandas%20Didn%E2%80%99t%20Stand%20a%20Chance.)
  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fi-rewrote-a-real-data-workflow-in-polars-pandas-didnt-stand-a-chance%2F&text=I%20Rewrote%20a%20Real%20Data%20Workflow%20in%20Polars.%20Pandas%20Didn%E2%80%99t%20Stand%20a%20Chance.)


Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.
[Write for TDS](https://towardsdatascience.com/submissions/)
## Related Articles
  * [![](../images/001.jpg)](https://towardsdatascience.com/resources-to-begin-your-artificial-intelligence-and-machine-learning-journey-7767a7d30831/)
## [Resources to Begin Your Data Science Journey Now](https://towardsdatascience.com/resources-to-begin-your-artificial-intelligence-and-machine-learning-journey-7767a7d30831/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
Start Your Data Science Journey Now
[Pranjal Saxena](https://towardsdatascience.com/author/pranjalai/)
October 14, 20203 min read
  * [![](../images/002.jpg)](https://towardsdatascience.com/training-a-model-on-google-ai-platform-84ceff87b5f3/)
## [Training a model on Google's AI Platform](https://towardsdatascience.com/training-a-model-on-google-ai-platform-84ceff87b5f3/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
How to train a model in Python using Google Cloud services
[Matteo Felici](https://towardsdatascience.com/author/matteofelici87/)
September 2, 20207 min read
  * [![](../images/003.png)](https://towardsdatascience.com/a-flexible-framework-for-entity-resolution-da970732884a/)
## [A Flexible Framework for Entity Resolution](https://towardsdatascience.com/a-flexible-framework-for-entity-resolution-da970732884a/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
Hoyoung Jang & Cheng Lin | TMLS2019
[TDS Editors](https://towardsdatascience.com/author/towardsdatascience/)
June 24, 20201 min read
  * [![](../images/004.png)](https://towardsdatascience.com/gradio-vs-streamlit-vs-dash-vs-flask-d3defb1209a2/)
## [Gradio vs Streamlit vs Dash vs Flask](https://towardsdatascience.com/gradio-vs-streamlit-vs-dash-vs-flask-d3defb1209a2/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
Comparing several web UI tools for data science!
[Terence Shin, MSc, MBA](https://towardsdatascience.com/author/terenceshin/)
February 23, 20215 min read
  * [![](../images/005.jpg)](https://towardsdatascience.com/10-awesome-programming-projects-for-data-scientists-d2bf64f72ee4/)
## [10 Awesome Programming Projects for Data Scientists](https://towardsdatascience.com/10-awesome-programming-projects-for-data-scientists-d2bf64f72ee4/)
[Programming](https://towardsdatascience.com/category/programming/)
Original ideas to help you improve your coding and analysis
[Rory Spanton](https://towardsdatascience.com/author/roryspanton/)
August 19, 20208 min read
  * [![](../images/006.jpeg)](https://towardsdatascience.com/10-examples-to-master-python-tuples-6c606ed42b96/)
## [10 Examples to Master Python Tuples](https://towardsdatascience.com/10-examples-to-master-python-tuples-6c606ed42b96/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
A comprehensive practical guide
[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)
November 8, 20205 min read
  * [![](../images/007.png)](https://towardsdatascience.com/comprehensive-guide-to-crafting-a-perfect-cv-in-data-science-dd6294aeb444/)
## [Comprehensive Guide to Crafting a Perfect CV in Data Science](https://towardsdatascience.com/comprehensive-guide-to-crafting-a-perfect-cv-in-data-science-dd6294aeb444/)
[Data Science](https://towardsdatascience.com/category/data-science/)
Impress recruiters and land your dream job by creating a standout resume
[Slava Efimov](https://towardsdatascience.com/author/slavahead/)
October 22, 202419 min read
  * [![](../images/008.png)](https://towardsdatascience.com/understanding-synthetic-control-methods-dd9a291885a1/)
## [Understanding Synthetic Control Methods](https://towardsdatascience.com/understanding-synthetic-control-methods-dd9a291885a1/)
[Data Science](https://towardsdatascience.com/category/data-science/)
A detailed guide to one of the most popular causal inference techniques in the industry
[Matteo Courthoud](https://towardsdatascience.com/author/matteo.courthoud/)
July 30, 202215 min read
  * [![](../images/009.png)](https://towardsdatascience.com/beyond-english-implementing-a-multilingual-rag-solution-12ccba0428b6/)
## [Beyond English: Implementing a multilingual RAG solution](https://towardsdatascience.com/beyond-english-implementing-a-multilingual-rag-solution-12ccba0428b6/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
An introduction to the do's and don'ts when implementing a non-english Retrieval Augmented Generation (RAG) system
[Jesper Alkestrup](https://towardsdatascience.com/author/jalkestrup/)
December 20, 202318 min read


  * [YouTube](https://www.youtube.com/c/TowardsDataScience)
  * [X](https://x.com/TDataScience)
  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)
  * [Threads](https://www.threads.net/@towardsdatascience)
  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)


[](https://towardsdatascience.com/)
Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.
Subscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)
© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)
####  Recommended Articles 
Close
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ "Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ "The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ "Does Your Company Have a Data Strategy?")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ "Productivity Tips, Data Career Insights, and Other Recent Must-Reads")


