typestar

SQL over frames in Python

Polars will run SQL against registered frames, planner and all.

import polars as pl

runs = pl.DataFrame({
    "lang": ["python", "rust", "python"],
    "tpm": [104, 98, 91],
})

with pl.SQLContext(runs=runs) as ctx:
    answer = ctx.execute(
        "SELECT lang, COUNT(*) AS n, AVG(tpm) AS mean_tpm "
        "FROM runs GROUP BY lang ORDER BY mean_tpm DESC",
        eager=True)
    print(answer)

print(runs.sql("SELECT * FROM self WHERE tpm > 95"))

How it works

  1. SQLContext registers frames under names.
  2. execute returns a LazyFrame unless you ask to collect.
  3. DataFrame.sql is the shorthand for one frame.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
348
Tokens
87
Three-star pace
115 tpm

At the three-star pace of 115 tokens a minute, this run takes about 45 seconds.

Type this snippet

Step 3 of 4 in Lazy & SQL, step 27 of 32 in Polars.

← Previous Next →