Skip to main content

polars-random

polars-random

PyPI version Python versions License: MIT CI Docs

Generate random numbers and statistical distributions natively in Polars DataFrames — a NumPy-style random API exposed as first-class Polars expressions, with reproducible seeds and per-row parameters.

polars-random is a Rust plugin offering four equivalent entry points so it composes naturally with the rest of polars:

Use case API
"Add a column of random draws to a DataFrame" df.random.<dist>(...)
Same thing, lazy lf.random.<dist>(...)
Inside any expression / with_columns / select pl.col("x").random.<dist>(...)  or  polars_random.<dist>(...)
Just give me N values as a Series polars_random.<dist>(..., size=N)
import polars as pl
import polars_random as pr  # registers DataFrame/LazyFrame/Expr namespaces

# 1. eager Series
pr.normal(mean=0.0, std=1.0, size=5, seed=42)

# 2. as a polars expression in any context
df = pl.DataFrame({"id": range(5)})
df.with_columns(noise=pr.normal(mean=0.0, std=1.0, seed=42))
df.with_columns(noise=pl.col("id").random.normal(seed=42))

# 3. as a DataFrame method (returns a new DataFrame with the column appended)
df.random.normal(mean=0.0, std=1.0, seed=42, name="noise")

# 4. inside a lazy pipeline
df.lazy().random.normal(seed=42, name="noise").collect()

Available distributions: rand / uniform, normal, binomial, randint. Every parameter (low, high, mean, std, n, p) accepts a Python scalar, a column name ("my_col"), or any pl.Expr. Nulls in column-valued parameters propagate as null in the output (no panic).

Why polars-random?

  • Polars-native — outputs are regular Polars columns, composable with the rest of your pipeline (no NumPy round-trips).
  • Per-row parameters — mean, std, low, high, n, p can come from other columns, so each row can be drawn from a different distribution.
  • Reproducible — pass seed=... per call, or set one global seed with pr.set_random_seed(...).
  • Fast — implemented in Rust on top of rand / rand_distr.

Installation

Requires Python 3.11+ and Polars 2.1+. For older Python or Polars versions, use polars-random<0.6.

uv add polars-random
poetry add polars-random
pip install polars-random

How it works (mental model)

Every distribution follows the same shape:

df.random.<distribution>(<params>, seed=None, name=None)
  • <params> are the distribution's parameters (e.g. low/high, mean/std, n/p).
  • Each parameter accepts a Python literal, a column name as a string, or a Polars expression (pl.col(...), arithmetic, etc.). Within a single call, all distribution parameters must be the same kind — either all literals or all expressions/column-names (no mixing).
  • seed makes the draw reproducible. Omit it for entropy-based randomness.
  • name is the new column's name. Defaults to the distribution name ("rand", "normal", "binomial").
  • The result is a new pl.DataFrame with the column appended. Calls chain.

Coming from NumPy?

NumPy polars-random
np.random.uniform(low, high, size=n) pr.rand(low=low, high=high, size=n)  or  df.random.rand(low=low, high=high)
np.random.normal(mean, std, size=n) pr.normal(mean=mean, std=std, size=n)
np.random.binomial(n, p, size=size) pr.binomial(n=n, p=p, size=size)
np.random.randint(low, high, size=n) pr.randint(low=low, high=high, size=n)
np.random.seed(42) (global) pr.set_random_seed(42) (global)  or  seed=42 per call
Different params per row (loop / vectorize manually) Pass a column name or pl.col(...) as the parameter

When used as a DataFrame/LazyFrame method or via the pl.col(...).random namespace, the output length is taken from the parent — no size= needed. Use size=N only with the top-level functions for "give me N values without a frame."

Seeding & reproducibility

Every draw takes an optional seed=. There are two ways to make results reproducible:

Per call — pass seed= to a single expression:

pr.normal(mean=0.0, std=1.0, seed=42)

Globally — set one seed once with pr.set_random_seed(...). Any draw that omits seed= then derives its seed from this global generator:

import polars as pl
import polars_random as pr

pr.set_random_seed(42)

df = pl.DataFrame({"id": range(5)})
df.with_columns(
    a=pr.normal(),               # reproducible — no per-call seed needed
    b=pr.rand(),                 # independent of `a`, also reproducible
)

This solves the "keep the distribution definition separate from where I set the seed" workflow: define length-free expressions (pr.normal(3.0, 1.0)) and let one global seed make the whole run reproducible, without threading seed=42 through every call.

Semantics:

  • Each expression consumes the global generator once, so distinct random columns in the same query stay independent (they are not byte-for-byte identical), just like NumPy's global RNG or polars' own set_random_seed.
  • Re-calling pr.set_random_seed(42) rewinds the sequence, so a script re-run reproduces the same draws.
  • An explicit seed= on a call always overrides the global seed for that call.
  • Without any global seed, seedless draws use OS entropy (the historical default) — nothing changes for existing code.

Chunking and execution engines

Each random expression generates one continuous sequence over its full input. With the same seed and ordered inputs, eager evaluation, lazy in-memory evaluation, and collect(engine="streaming") produce the same draws, regardless of input chunk boundaries. Null column parameters still produce null outputs.

Random expressions require the full input in memory, even in streaming queries. Polars can stream the surrounding query, but random generation is evaluated as a whole-column operation to preserve the RNG sequence.

Want two identical columns?

Seedless draws under a global seed are always independent (that is the point), so they never coincide. To make two columns equal, give them the same explicit seed= — that pins both to the same draw and bypasses the global generator:

df.with_columns(
    a=pr.normal(seed=7),
    b=pr.normal(seed=7),   # a == b, byte-for-byte
)

Reproducibility depends on call order

Under a global seed, each seedless draw takes the next value from the generator, so reproducibility depends on the order and number of seedless draws — the same sequence of calls reproduces the same columns. Inserting or reordering a seedless draw shifts every later one (exactly like NumPy's or Polars' global RNG). If a specific column must stay fixed regardless of surrounding code, pin it with an explicit seed=.

pr.set_random_seed is independent of polars.set_random_seed. Polars seeds its own operations (.sample(), .shuffle(), …) and exposes only a setter — there is no public way for a plugin to read Polars' seed — so polars-random keeps its own global seed. Set both if you want Polars and polars-random reproducible in the same script.

Distributions

df.random.rand (uniform) · also aliased as df.random.uniform

Parameter Type Default Description
low float, str, pl.Expr, or None 0.0 Lower bound (inclusive).
high float, str, pl.Expr, or None 1.0 Upper bound (exclusive).
seed int or None None Reproducible draws.
name str or None "rand" Output column name.
import polars as pl
import polars_random

df = pl.DataFrame({
    "custom_low":  [0.0, 10.0, 100.0],
    "custom_high": [1.0, 20.0, 200.0],
})

(
    df
    # Scalar parameters
    .random.rand(low=1_000., high=2_000., seed=42, name="rand_scalar")
    # Default range [0, 1)
    .random.rand(seed=42, name="rand_default")
    # Per-row parameters via expression
    .random.rand(low=pl.col("custom_low"), high=pl.col("custom_high"), seed=42, name="rand_expr")
    # Per-row parameters via column name
    .random.rand(low="custom_low", high="custom_high", seed=42, name="rand_str")
)

df.random.normal

Parameter Type Default Description
mean float, str, pl.Expr, or None 0.0 Mean of the normal distribution.
std float, str, pl.Expr, or None 1.0 Standard deviation (must be > 0).
seed int or None None Reproducible draws.
name str or None "normal" Output column name.
import polars as pl
import polars_random

df = pl.DataFrame({
    "custom_mean": [0.0, 5.0, -3.0],
    "custom_std":  [1.0, 2.0, 0.5],
})

(
    df
    .random.normal(mean=3., std=2., seed=42, name="normal_scalar")
    .random.normal(seed=42, name="normal_default")  # mean=0, std=1
    .random.normal(mean=pl.col("custom_mean"), std=pl.col("custom_std"), seed=42, name="normal_expr")
    .random.normal(mean="custom_mean", std="custom_std", seed=42, name="normal_str")
)

df.random.binomial

Parameter Type Default Description
n int, str, or pl.Expr (required) Number of trials.
p float, str, or pl.Expr (required) Probability of success on each trial (0 ≤ p ≤ 1).
seed int or None None Reproducible draws.
name str or None "binomial" Output column name.
import polars as pl
import polars_random

df = pl.DataFrame({
    "n": [10, 50, 100],
    "p": [0.1, 0.5, 0.9],
})

(
    df
    .random.binomial(n=100, p=.5, seed=42, name="binomial_scalar")
    .random.binomial(n=pl.col("n"), p=pl.col("p"), seed=42, name="binomial_expr")
    .random.binomial(n="n", p="p", seed=42, name="binomial_str")
)

df.random.randint

Uniform random integers in [low, high) (high is exclusive, matching numpy.random.randint).

Parameter Type Default Description
low int, str, or pl.Expr 0 Lower bound (inclusive).
high int, str, or pl.Expr 2 Upper bound (exclusive).
seed int or None None Reproducible draws.
name str or None "randint" Output column name.
df.random.randint(low=0, high=10, seed=42)            # one column, scalar bounds
df.random.randint(low="lo", high="hi", seed=42)       # per-row bounds via columns

Beyond df.random — same kernel, four entry points

import polars as pl
import polars_random as pr

# 1. Top-level: returns a Series of N random values (NumPy-style).
pr.normal(mean=0, std=1, size=1_000, seed=42)

# 2. Top-level inside any expression (length comes from the surrounding context).
df.with_columns(noise=pr.normal(mean=0, std=1, seed=42))

# 3. Expression namespace — anchor random draws to an existing column.
df.with_columns(noise=pl.col("id").random.normal(mean=0, std=1, seed=42))

# 4. LazyFrame — keep random draws inside a lazy plan.
df.lazy().random.binomial(n=10, p=0.5, seed=42, name="trials").collect()

When a parameter is column-valued (pl.col(...), a column name, or any expression) and contains nulls, the output is null at those rows instead of raising.

Benchmarks

polars-random generates draws in Rust using rand / rand_distr. The benchmark compares NumPy with eager expressions, lazy in-memory queries, and queries using the streaming engine. Seeded outputs are checked for equality across these Polars scenarios before timing them.

Random generation runs over the full input in every engine. Earlier releases incorrectly advertised streaming parallelism: each chunk restarted the same seeded sequence. Those streaming results contained repeated samples and are not representative of correct generation in 0.6.0 and later.

Timings depend on your machine and distribution. Run the benchmark below for current measurements; the committed results record the exact package versions and environment used.

Reproducing

# release build of the Rust extension
just install-release

# run the benchmark (writes benchmarks/results.md and benchmarks/results.json)
just bench

just bench is equivalent to:

uv run --with numpy python benchmarks/benchmark.py

The script accepts --sizes, --repeats, --inner, --output, and --json flags; see python benchmarks/benchmark.py --help. Defaults are --sizes 10000,100000,1000000,10000000,50000000 --repeats 5 --inner 2.

Documentation

Full API reference: https://diegoglozano.github.io/polars-random/

License

MIT

Metadata

Release files for polars-random 0.6.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for polars-random 0.6.0
File Size Uploaded Provenance Actions
polars_random-0.6.0.tar.gz 106.7 kB Without provenance Details for polars_random-0.6.0.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for polars-random 0.6.0
File Actions
polars_random-0.6.0-cp311-abi3-win_amd64.whl CPython 3.11 abi3 Windows x86-64 Details for polars_random-0.6.0-cp311-abi3-win_amd64.whl
polars_random-0.6.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl CPython 3.11 abi3 Linux glibc 2.17+ x86-64 Details for polars_random-0.6.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
polars_random-0.6.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl CPython 3.11 abi3 Linux glibc 2.17+ ARM64 Details for polars_random-0.6.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
polars_random-0.6.0-cp311-abi3-macosx_11_0_arm64.whl CPython 3.11 abi3 macOS 11.0+ ARM64 Details for polars_random-0.6.0-cp311-abi3-macosx_11_0_arm64.whl
polars_random-0.6.0-cp311-abi3-macosx_10_12_x86_64.whl CPython 3.11 abi3 macOS 10.12+ x86-64 Details for polars_random-0.6.0-cp311-abi3-macosx_10_12_x86_64.whl

Total release size: 24.0 MB

Release files / polars_random-0.6.0.tar.gz

Download URL polars_random-0.6.0.tar.gz
Size 106.7 kB
Tags Source
SHA-256 checksum
How to use checksums
e2000d60d9e374b50faf75610a56189600263b69d2076471d7f91e943103bc9f
BLAKE2b-256 checksum
How to use checksums
af3077c65302a153d07c75e5a71111dc279e3536ad3e3c6a36029bc722a7a839
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via maturin/1.16.0

Release files / polars_random-0.6.0-cp311-abi3-win_amd64.whl

Download URL polars_random-0.6.0-cp311-abi3-win_amd64.whl
Size 4.7 MB
Tags CPython 3.11 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
2dfd240337d3f01b7b7366db78474240971142eafc84ebea8f34148d40471c96
BLAKE2b-256 checksum
How to use checksums
3d7852cb072dd40816f32ce9a24951c011a47e568b05d92f05a3026d6cbc51b9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via maturin/1.16.0

Release files / polars_random-0.6.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl

Download URL polars_random-0.6.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 5.4 MB
Tags CPython 3.11 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
7aac38dc73503696dd3e0bd262660c9760c8035f5eb711febff7e93343261327
BLAKE2b-256 checksum
How to use checksums
6c85110b613eb1a030670eada2352449bfba98a13a387f8cbfc49b21520eeebf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via maturin/1.16.0

Release files / polars_random-0.6.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl

Download URL polars_random-0.6.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
Size 4.8 MB
Tags CPython 3.11 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
df86e0f11d4453db6704c517e557bdd2c902891f58c62aca8b17362d0d163fa1
BLAKE2b-256 checksum
How to use checksums
5dfe6d42d6612e8bbfd3f043832ef52b5333d9c7499857453204ced45e7109df
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via maturin/1.16.0

Release files / polars_random-0.6.0-cp311-abi3-macosx_11_0_arm64.whl

Download URL polars_random-0.6.0-cp311-abi3-macosx_11_0_arm64.whl
Size 4.4 MB
Tags CPython 3.11 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
13012b9217a16e40f3ee88794db8f4ee5fb58f2cf3a067b7a1d8bedfe658d3c8
BLAKE2b-256 checksum
How to use checksums
239edde1be47b3c7f667eabf6e887d398fbb4592ddbf168c3810e584a02121c8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via maturin/1.16.0

Release files / polars_random-0.6.0-cp311-abi3-macosx_10_12_x86_64.whl

Download URL polars_random-0.6.0-cp311-abi3-macosx_10_12_x86_64.whl
Size 4.7 MB
Tags CPython 3.11 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
25ae21119b3ee74bf54a17f5b601b4804ebe06a10e7b0a8a880f5e3a13929a5a
BLAKE2b-256 checksum
How to use checksums
7bb33f70ac5abfe901a950174fea4d930b63e41363d711029ac92bc7a68fa064
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via maturin/1.16.0

Security for polars-random 0.6.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page