r/Python • • 4h ago

Showcase Showcase Thread

Post all of your code/projects/showcases/AI slop here.

Recycles once a month.

8 Upvotes

19 comments sorted by

View all comments

•

u/import_pandas_as_np 41m ago

polars-stats: scipy.stats-style probability distributions as Polars expressions, with per-row parameters

What My Project Does

polars-stats brings scipy.stats-style probability distributions into Polars as native expressions: densities, cdf/sf, quantiles (ppf/isf), their log variants, moments and seeded sampling. Parameters can be columns, so one expression evaluates a different distribution on every row, inside a lazy query.

import polars as pl
import polars_stats as ps

readings = pl.LazyFrame({
    "sensor": ["a", "b", "c"],
    "baseline": [20.0, 35.0, 12.0],
    "noise": [0.5, 2.0, 1.0],
    "reading": [21.7, 34.0, 15.5],
})

dist = ps.Normal(mu="baseline", sigma="noise")
alerts = (
    readings.with_columns(
        p_value=dist.sf("reading"),   # P(X > reading) under each sensor's own baseline
        alert_above=dist.isf(0.001),  # each sensor's own threshold
    )
    .filter(pl.col("p_value") < 0.01)
    .collect()
)
  • The common continuous and discrete distributions: Normal, LogNormal, Gamma, Beta, Student's t, Poisson, Binomial and more.

  • Nulls propagate per row; an invalid parameter raises instead of turning into NaN.

  • sample(seed=...) gives the same draws on the in-memory and streaming engines, at any thread count.

  • log_sf / log_cdf stay finite deep in the tails, tested against an arbitrary-precision oracle (mpmath).

  • Rust underneath, built on statrs.

Target Audience

People who already keep their data in Polars and need per-row probability work: anomaly scoring against per-entity baselines, posterior intervals per A/B variant, Monte Carlo simulation inside a pipeline.

It is a young project, tested against scipy on every distribution and method; method names follow scipy.

Requests for missing distributions are welcome.

Comparison

  • scipy.stats already vectorises per-row parameters (norm(loc=mu, scale=sigma).sf(x)), and it is the reference polars-stats is tested against. The difference is where the result lands: scipy returns a NumPy array, so a lazy query has to collect, convert, and stitch the result back in, and nulls become NaN. polars-stats stays an expression, so the optimiser keeps working around it (a later filter is still pushed down).

  • map_batches with scipy inside keeps the work in the plan, but as an opaque Python callback.

  • Performance: at 1M rows with a different distribution on every row, the median speedup over scipy's frozen API is about 8x for pdf/cdf/sf, almost 10x for ppf/isf and 7x for sampling, on a 10-core machine with Polars on all cores. On 10k rows the gain is 1.3x to 1.6x, and single-number moments are slower because of query overhead. Full grid and the script to reproduce it: https://fbruzzesi.github.io/polars-stats/performance/

Links: