Crunching data? Put that laptop hardware to use

Crunching data? Put that laptop hardware to use

Let’s say a utility company has 10,000 electricity meters and let’s say each meter reports a reading every 15 minutes. When you do the math, that’s 960,000 readings per day and about 350 million per year. Let’s also say that the readings arrive as one compressed CSV file per day because, sooner or later, every data pipeline becomes a directory full of CSV files. It doesn’t take long for this to become an inconveniently sized dataset to try to analyze on your laptop, but there are many ways to push what your laptop can handle thanks to modern tools in the python data ecosystem.

So, suppose we start from a directory that looks like this:

$ ls data/readings | head
2025-06-01.csv.gz
2025-06-02.csv.gz
2025-06-03.csv.gz
...

Each row in the files is straightforward:

meter_id,timestamp,kwh,voltage
M000000,2025-06-01T00:00:00.000000,0.12,238.0
M000000,2025-06-01T00:15:00.000000,0.12,237.93

An analyst asks a small question:

For these 25 meters in particular, what was the daily energy use during July?

The whole dataset is big, but the query doesn’t care about much of it. We only need 25 meters, one month, and three of the five columns.

This article starts with the obvious pandas solution, then improves how we read, store, and query the data. Along the way we’ll use Polars, Parquet, DuckDB, PyArrow, Ibis, and SQLGlot.

That sounds like a lot of tools, but each one serves a certain purpose in this story, and I’ll try to help you understand when you might want to reach for one.

Sidebar about the test data

The full system would produce 350 million rows per year, which is an inconvenient amount of synthetic data to publish with an article. I generated a smaller sample with the same shape:

  • 1,000 meters
  • one reading every 15 minutes
  • 90 daily CSV files, from June through August
  • 8,640,000 rows
  • 451 MiB of CSV, or 42 MiB after gzip compression

The values are deterministic so that generation gives the same data each time. This makes the data repetitive, so the storage results are more flattering than real readings would be. Meter usage varies by meter, time of day, and day of week.

We’ll walk through several implementations, and we’ll have each implementation answer the same July query. I measured elapsed time and peak process memory.

I ran each implementation three times in a fresh process and reported the median. The machine was an Apple M3 Max with 48 GiB of memory, running Python 3.14.2.

The obvious pandas solution

The first version reads every file, concatenates the DataFrames, filters July, and aggregates the selected meters:

import glob
import pandas as pd

readings = pd.concat(
  pd.read_csv(path, parse_dates=["timestamp"])
  for path in glob.glob("data/readings/*.csv.gz")
)

selected = readings[
  readings["meter_id"].isin(selected_meters)
  & readings["timestamp"].between(
    "2025-07-01", "2025-08-01", inclusive="left"
  )
].copy()
selected["day"] = selected["timestamp"].dt.date

result = (
  selected
  .groupby(["meter_id", "day"], as_index=False)["kwh"]
  .sum()
)

It works:

Time          3.80 seconds
Peak memory   1,145 MB

For 8.6 million rows, four seconds is not disastrous. The memory use is more interesting. We used more than a gigabyte to produce 775 rows.

This isn’t really the fault of pandas, it’s not the problem per se. The real problem is just in the approach: “Load first, ask questions later”.

The code does exactly what we asked. It opens all 90 files, parses all of the columns, creates one large DataFrame, and only then discards nearly everything.

Let Polars inspect the query first

Polars has an eager DataFrame API, but the useful feature for this problem is its lazy API.

Instead of reading a CSV into a DataFrame, scan_csv creates a LazyFrame:

import polars as pl

query = (
  pl.scan_csv("data/readings/*.csv.gz", try_parse_dates=True)
  .filter(
    pl.col("meter_id").is_in(selected_meters),
    pl.col("timestamp").is_between(
      pl.datetime(2025, 7, 1),
      pl.datetime(2025, 8, 1),
      closed="left",
    ),
  )
  .group_by(
    "meter_id",
    pl.col("timestamp").dt.date().alias("day"),
  )
  .agg(pl.col("kwh").sum())
)

result = query.collect()

Nothing happens until collect(). Before executing the query, Polars can inspect the entire operation and optimize it. In particular, it knows that the result only needs meter_id, timestamp, and kwh. There are fancy terms for this like “projection pushdown” and “predicate pushdown” that make for interesting reading but I won’t go into them here.

The result:

Time          0.47 seconds
Peak memory   539 MB

That is about eight times faster than the pandas version and uses less than half the memory.

This is already a useful improvement, but we still parse 90 compressed text files every time someone changes the query. CSV is a fairly naive storage format, it only stores characters. This makes it convenient and human-readable, but not very powerful. Powerful solutions can do things like preserve a timestamp type, numeric encoding, or useful statistics about groups of rows.

If we plan to query the readings more than once, we should stop paying the CSV tax.

Pay CSV tax once, get Parquet back

Parquet is a columnar file format. Unlike a row-based format, values from the same column are stored together, types are preserved, and metadata describes groups of rows. With this layout, an engine can read the three columns in our query without reading voltage or quality. Depending on the file layout and statistics, it may also skip groups that cannot match the date filter.

Polars can convert the CSV files to Parquet files with one lazy operation:

(
  pl.scan_csv("data/readings/*.csv.gz", try_parse_dates=True)
  .sink_parquet("data/readings.parquet")
)

sink_parquet can execute a lazy query in streaming mode. That’s especially useful when the input is larger than memory, but it’s nice even when it’s not.

For this sample, conversion took 0.50 seconds. The 42 MiB of compressed CSV became a 1.5 MiB Parquet file.

A short aside: like I mentioned at the beginning, this is fake data. With the repetitive data I fed into this, Parquet was very good at compressing it. With real data, you probably can’t expect that much compression.

Now with our parquet file, we have typed columnar storage that many analytical tools will understand.

The Polars query barely changes to read from the parquet file instead:

query = (
  pl.scan_parquet("data/readings.parquet")
  .filter(
    pl.col("meter_id").is_in(selected_meters),
    pl.col("timestamp").is_between(
      pl.datetime(2025, 7, 1),
      pl.datetime(2025, 8, 1),
      closed="left",
    ),
  )
  .group_by(
    "meter_id",
    pl.col("timestamp").dt.date().alias("day"),
  )
  .agg(pl.col("kwh").sum())
)

result = query.collect()

The result does change:

Time          0.058 seconds
Peak memory   124 MB

Compared with the original pandas query, this is about 65 times faster and uses about one ninth of the memory.

This improvement is thanks to storing our data in a format designed to be queried for analytical purposes.

Query the files with DuckDB

Let’s revisit our hypothetical story. The analyst who asked for this report probably already knows SQL, but maybe they’re less comfortable with python. Writing the query as a chain of DataFrame operations might not be what that person had in mind. Luckily we have another amazing tool called DuckDB available to us that is easy to use in python, which will let us continue to use SQL while seeing awesome performance improvements.

DuckDB is an in-process analytical database. This is similar to sqlite, but again the columnar storage format is in play instead. There is no server to install and no database service to operate. The Python package can query Parquet files directly:

import duckdb

result = duckdb.execute(
  """
  SELECT
    meter_id,
    CAST(timestamp AS DATE) AS day,
    SUM(kwh) AS kwh
  FROM read_parquet(?)
  WHERE
    timestamp >= ?
    AND timestamp < ?
    AND meter_id = ANY(?)
  GROUP BY ALL
  """,
  [
    "data/readings.parquet",
    "2025-07-01",
    "2025-08-01",
    selected_meters,
  ],
).to_arrow_table()

Note: the parameters are bound rather than pasted into the SQL string. Even in an example, constructing SQL from values is a habit best avoided. 🙂

DuckDB applies projection and filter pushdown to Parquet scans. It also runs the aggregation inside the engine rather than creating Python objects for millions of input rows.

Time          0.20 seconds
Peak memory   165 MB

Polars was faster for this particular query. DuckDB is still comfortably fast, and the implementation is plain SQL. It can also join the Parquet readings to CSV files, DataFrames, Arrow tables, and database results without first building a permanent DuckDB database!

Fortunately, you’re never really stuck with using just one option. All the of the tools mentioned so far work with something called Apache Arrow, which makes passing data around between tools really efficient.

The common language is Arrow

Parquet and Arrow are often mentioned together, which makes them easy to confuse.

Parquet is a storage format. It describes columnar data on disk.

Apache Arrow is an in-memory format and a set of interchange interfaces. It describes how columnar arrays, record batches, schemas, and buffers can be represented and exchanged.

PyArrow is the Python package for Apache Arrow. It gives Python programs access to Arrow arrays, tables, record batches, Parquet readers and writers, datasets, compute functions, and interchange APIs.

I would guess that most people don’t use PyArrow directly, but you can use it query the Parquet dataset directly:

import datetime
import pyarrow as pa
import pyarrow.dataset as ds

readings = ds.dataset("data/readings.parquet", format="parquet")

july = readings.to_table(
  columns=["meter_id", "timestamp", "kwh"],
  filter=(
    (ds.field("timestamp") >= pa.scalar(
      datetime.datetime(2025, 7, 1),
      type=pa.timestamp("us"),
    ))
    & (ds.field("timestamp") < pa.scalar(
      datetime.datetime(2025, 8, 1),
      type=pa.timestamp("us"),
    ))
    & ds.field("meter_id").isin(selected_meters)
  ),
)

We can do the same things we wanted before, but it’s not as pleasant to use directly.

Instead, let’s revisit the result call in the DuckDB example:

arrow_result = duckdb.execute(sql, parameters).to_arrow_table()

DuckDB returns a PyArrow table. We can hand Arrow output to Polars:

reader = duckdb.sql("""
  SELECT meter_id, kwh
  FROM read_parquet('data/readings.parquet')
  LIMIT 10
""").arrow()

result = pl.from_arrow(reader)

assert result.shape == (10, 2)

DuckDB returns a pyarrow.RecordBatchReader, and Polars consumes it directly. We do not loop over rows or convert every number and timestamp into a separate Python object.

This compatibility is by design to make it so libraries can exchange data through those Arrow interfaces instead of writing a custom converter for every pair of tools. Our great performance exchanging data between these tools is thanks to the compatible columnar systems having a direct route that does not require turning the dataset into Python rows.

PyArrow also connects this workflow back to older tools. Modern Pandas can use Arrow-backed dtypes and convert to and from Arrow tables. The next tool I’ll mention also commonly returns Arrow tables and record batches. Many data systems outside Python implement the same interfaces as well.

To recap: Parquet makes the readings reusable on disk. Arrow helps the tools share them in memory. PyArrow is where Python gets access to both.

So, what if everyone on your team is using different tools to do similar analyses? That would be annoying.

Write the expression once with Ibis

We now have a Polars expression and a DuckDB SQL query that describe the same calculation. That is fine for one report. It becomes less appealing if a project has dozens of calculations and may run them on different engines.

Ibis provides a shared language for speaking across the different DataFrame APIs. You build an expression, then a backend compiles and executes it.

import ibis

con = ibis.duckdb.connect()
readings = con.read_parquet(
  "data/readings.parquet",
  table_name="readings",
)

filtered = readings.filter(
  readings.timestamp >= "2025-07-01",
  readings.timestamp < "2025-08-01",
  readings.meter_id.isin(selected_meters),
)

result = (
  filtered
  .mutate(day=filtered.timestamp.date())
  .group_by("meter_id", "day")
  .aggregate(kwh=lambda table: table.kwh.sum())
)

The expression has not executed yet. We can inspect the SQL Ibis generates:

print(ibis.to_sql(result, dialect="duckdb"))

Or execute it and receive an Arrow table:

result.to_pyarrow()

The same style of expression can target other Ibis backends, including Polars and remote databases. Ibis compiles the expression for the selected backend, so the same calculation can produce DuckDB SQL locally and a different dialect in a warehouse like BigQuery.

If you’re curious about how all of this SQL translation happens across backends, take a look at the tool underneath the hood, SQLGlot:

from sqlglot import transpile

bigquery_sql = transpile(
  duckdb_sql,
  read="duckdb",
  write="bigquery",
)[0]

Results

These are the median results from three runs.

Approach Input Time Peak memory Result
pandas gzip CSV 3.80 s 1,145 MB 775 rows
Polars lazy gzip CSV 0.47 s 539 MB 775 rows
Polars lazy Parquet 0.058 s 124 MB 775 rows
DuckDB Parquet 0.20 s 165 MB 775 rows

The one-time CSV-to-Parquet conversion took 0.50 seconds and peaked at 589 MB. In this fake test, conversion paid for itself almost immediately.

So, what have we learned?

  • Eagerly loading all the input is expensive when the query needs a small fraction of it.
  • Lazy execution lets an engine discard work earlier.
  • Repeatedly parsing CSV wastes time.
  • Parquet gives analytical engines more useful storage.
  • Arrow lets those engines exchange columnar data efficiently.

What should you use?

If your data fits comfortably in memory and the existing pandas code is fast enough, keep it. After all, most folks dipping their toes in this water are probably familiar with pandas.

If you want a DataFrame API but eager execution or memory use has become a problem, try a Polars lazy query.

If you query the same CSV data repeatedly, convert it to Parquet.

If the question is naturally SQL, query the Parquet files with DuckDB. You do not need to load them into a database first.

I’d suggest learning enough PyArrow to be able to recognize an Arrow table, inspect a schema, scan a dataset, and move batches between tools. You probably won’t call PyArrow in every analysis, but much of the compatibility in the Python data ecosystem makes more sense once you understand what it provides.

Use Ibis when one deferred expression needs to run through different backends. If the starting point is existing SQL that needs another dialect, use SQLGlot.

Want to work with Simple Thread?
Whether you’re looking for a technology partner or interested in joining our team, we’d love to hear from you.
Reach Out

Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

More Insights

View All

Run Better Studies.
Move Faster.

If your study process is becoming a bottleneck, we can help you run faster, more consistent workflows with confidence.

Talk to our team
California Consumer Privacy Act (CCPA) Opt-Out IconYour Privacy Choices