Skip to content

API reference

polars-random exposes the same set of distributions through four interchangeable entry points. Pick whichever fits your pipeline; the underlying Rust kernel is the same.

Top-level functions

Returns a pl.Expr by default, or a pl.Series of length size when size= is given.

Uniform [low, high) random draws.

Parameters:

Name Type Description Default
low float, str (column name), pl.Expr, or None

Distribution bounds. Must both be scalars or both be column-like. Defaults to [0.0, 1.0).

None
high float, str (column name), pl.Expr, or None

Distribution bounds. Must both be scalars or both be column-like. Defaults to [0.0, 1.0).

None
seed int or None

Reproducible draws.

None
size (int or None, keyword - only)

If given, eagerly evaluate and return a Series of that length. Otherwise returns a polars Expr to be used in a select/with_columns.

None

Returns:

Type Description
Expr or Series
Source code in polars_random/__init__.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def rand(
    low: FloatParam = None,
    high: FloatParam = None,
    seed: int | None = None,
    *,
    size: int | None = None,
) -> pl.Expr | pl.Series:
    """
    Uniform `[low, high)` random draws.

    Parameters
    ----------
    low, high : float, str (column name), pl.Expr, or None
        Distribution bounds. Must both be scalars or both be column-like.
        Defaults to ``[0.0, 1.0)``.
    seed : int or None, optional
        Reproducible draws.
    size : int or None, keyword-only
        If given, eagerly evaluate and return a Series of that length.
        Otherwise returns a polars Expr to be used in a select/with_columns.

    Returns
    -------
    pl.Expr or pl.Series
    """
    _check_size(size)
    if size is None:
        return _rand_expr(low=low, high=high, seed=seed)
    over = pl.int_range(0, size).cast(pl.Float64)
    return _eager(_rand_expr(low=low, high=high, seed=seed, over=over).alias("rand"), size)

Normal (Gaussian) random draws.

Parameters:

Name Type Description Default
mean float, str (column name), pl.Expr, or None

Distribution parameters. Must both be scalars or both be column-like.

0.0
std float, str (column name), pl.Expr, or None

Distribution parameters. Must both be scalars or both be column-like.

0.0
seed int or None
None
size (int or None, keyword - only)

If given, eagerly evaluate and return a Series of that length.

None

Returns:

Type Description
Expr or Series
Source code in polars_random/__init__.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def normal(
    mean: FloatParam = 0.0,
    std: FloatParam = 1.0,
    seed: int | None = None,
    *,
    size: int | None = None,
) -> pl.Expr | pl.Series:
    """
    Normal (Gaussian) random draws.

    Parameters
    ----------
    mean, std : float, str (column name), pl.Expr, or None
        Distribution parameters. Must both be scalars or both be column-like.
    seed : int or None, optional
    size : int or None, keyword-only
        If given, eagerly evaluate and return a Series of that length.

    Returns
    -------
    pl.Expr or pl.Series
    """
    _check_size(size)
    if size is None:
        return _normal_expr(mean=mean, std=std, seed=seed)
    over = pl.int_range(0, size).cast(pl.Float64)
    return _eager(_normal_expr(mean=mean, std=std, seed=seed, over=over).alias("normal"), size)

Binomial random draws.

Parameters:

Name Type Description Default
n int, str (column name), or pl.Expr

Number of trials.

required
p float, str (column name), or pl.Expr

Probability of success.

required
seed int or None
None
size (int or None, keyword - only)

If given, eagerly evaluate and return a Series of that length.

None

Returns:

Type Description
Expr or Series
Source code in polars_random/__init__.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def binomial(
    n: IntParam,
    p: FloatParam,
    seed: int | None = None,
    *,
    size: int | None = None,
) -> pl.Expr | pl.Series:
    """
    Binomial random draws.

    Parameters
    ----------
    n : int, str (column name), or pl.Expr
        Number of trials.
    p : float, str (column name), or pl.Expr
        Probability of success.
    seed : int or None, optional
    size : int or None, keyword-only
        If given, eagerly evaluate and return a Series of that length.

    Returns
    -------
    pl.Expr or pl.Series
    """
    _check_size(size)
    if size is None:
        return _binomial_expr(n=n, p=p, seed=seed)
    over = pl.int_range(0, size).cast(pl.Float64)
    return _eager(_binomial_expr(n=n, p=p, seed=seed, over=over).alias("binomial"), size)

Uniform random integers in [low, high).

Parameters:

Name Type Description Default
low int, str (column name), or pl.Expr

Bounds; high is exclusive. Must both be scalars or both be column-like.

0
high int, str (column name), or pl.Expr

Bounds; high is exclusive. Must both be scalars or both be column-like.

0
seed int or None
None
size (int or None, keyword - only)

If given, eagerly evaluate and return a Series of that length.

None

Returns:

Type Description
Expr or Series
Source code in polars_random/__init__.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def randint(
    low: IntParam = 0,
    high: IntParam = 2,
    seed: int | None = None,
    *,
    size: int | None = None,
) -> pl.Expr | pl.Series:
    """
    Uniform random integers in ``[low, high)``.

    Parameters
    ----------
    low, high : int, str (column name), or pl.Expr
        Bounds; ``high`` is exclusive. Must both be scalars or both be column-like.
    seed : int or None, optional
    size : int or None, keyword-only
        If given, eagerly evaluate and return a Series of that length.

    Returns
    -------
    pl.Expr or pl.Series
    """
    _check_size(size)
    if size is None:
        return _randint_expr(low=low, high=high, seed=seed)
    over = pl.int_range(0, size).cast(pl.Float64)
    return _eager(_randint_expr(low=low, high=high, seed=seed, over=over).alias("randint"), size)

Global seed

Set one seed for the whole session. Any draw that omits seed= then derives its seed from this global generator; an explicit seed= on a call still overrides it. Distinct expressions consume the generator separately, so they stay independent while remaining reproducible across re-runs.

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(), b=pr.rand())  # reproducible, no per-call seed

Reproducibility depends on the order and number of seedless draws (each takes the next value from the generator, like NumPy's or Polars' global RNG). To make two columns identical, give them the same explicit seed= — the global seed is designed to keep seedless draws independent:

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

pr.set_random_seed is independent of polars.set_random_seed (which seeds Polars' own .sample() / .shuffle() and is not readable by plugins).

Set a global default seed for all polars-random draws.

Once set, any polars-random expression that does not pass an explicit seed= derives its seed from this global generator. Each expression consumes the generator, so distinct random columns in the same query stay independent (not byte-for-byte identical) while the whole run remains reproducible. Re-calling set_random_seed with the same value rewinds the sequence, reproducing the same draws.

An explicit seed= on an individual call always overrides the global seed for that call. Because each seedless draw takes the next value from the generator, reproducibility depends on the order and number of seedless draws: inserting or reordering one shifts every later draw. To make two columns identical, give them the same explicit seed= rather than relying on the global seed (which is designed to keep them independent).

This is independent of :func:polars.set_random_seed, which seeds Polars' own operations (.sample(), .shuffle(), …) and is not readable by third-party plugins.

Parameters:

Name Type Description Default
seed int

A non-negative integer used to seed the internal global generator.

required

Examples:

>>> import polars as pl
>>> import polars_random as pr
>>> pr.set_random_seed(42)
>>> df = pl.DataFrame({"id": range(3)})
>>> a = df.with_columns(x=pr.normal())  # reproducible without seed=
>>> pr.set_random_seed(42)
>>> b = df.with_columns(x=pr.normal())
>>> a.equals(b)
True
Source code in polars_random/__init__.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def set_random_seed(seed: int) -> None:
    """
    Set a global default seed for all ``polars-random`` draws.

    Once set, any ``polars-random`` expression that does **not** pass an
    explicit ``seed=`` derives its seed from this global generator. Each
    expression consumes the generator, so distinct random columns in the same
    query stay independent (not byte-for-byte identical) while the whole run
    remains reproducible. Re-calling ``set_random_seed`` with the same value
    rewinds the sequence, reproducing the same draws.

    An explicit ``seed=`` on an individual call always overrides the global
    seed for that call. Because each seedless draw takes the *next* value from
    the generator, reproducibility depends on the order and number of seedless
    draws: inserting or reordering one shifts every later draw. To make two
    columns *identical*, give them the same explicit ``seed=`` rather than
    relying on the global seed (which is designed to keep them independent).

    This is independent of :func:`polars.set_random_seed`, which seeds Polars'
    own operations (``.sample()``, ``.shuffle()``, …) and is not readable by
    third-party plugins.

    Parameters
    ----------
    seed : int
        A non-negative integer used to seed the internal global generator.

    Examples
    --------
    >>> import polars as pl
    >>> import polars_random as pr
    >>> pr.set_random_seed(42)
    >>> df = pl.DataFrame({"id": range(3)})
    >>> a = df.with_columns(x=pr.normal())  # reproducible without seed=
    >>> pr.set_random_seed(42)
    >>> b = df.with_columns(x=pr.normal())
    >>> a.equals(b)
    True
    """
    if seed is None or seed < 0:
        raise ValueError("Seed must be a non-negative integer")
    global _GLOBAL_RNG
    _GLOBAL_RNG = _random.Random(seed)

pl.col(...).random — expression namespace

Use inside any expression context (select, with_columns, lazy queries, group-by aggregations, …). The parent expression provides the row count.

import polars as pl
import polars_random  # registers the namespace

df.with_columns(noise=pl.col("id").random.normal(mean=0, std=1, seed=42))

Available methods: rand / uniform, normal, binomial, randint. Same parameters as the top-level functions, minus size.

df.random — DataFrame namespace

Namespace for adding columns of random draws to a DataFrame.

Parameters:

Name Type Description Default
df DataFrame

The dataframe to apply the random functions on.

required
Source code in polars_random/__init__.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
@pl.api.register_dataframe_namespace("random")
class Random:
    """
    Namespace for adding columns of random draws to a ``DataFrame``.

    Parameters
    ----------
    df : pl.DataFrame
        The dataframe to apply the random functions on.
    """

    def __init__(self, df: pl.DataFrame) -> None:
        self._df = df

    def rand(
        self,
        low: FloatParam = None,
        high: FloatParam = None,
        seed: int | None = None,
        name: str | None = None,
    ) -> pl.DataFrame:
        return self._df.with_columns(
            _rand_expr(low=low, high=high, seed=seed).alias(name or "rand")
        )

    uniform = rand

    def normal(
        self,
        mean: FloatParam = 0.0,
        std: FloatParam = 1.0,
        seed: int | None = None,
        name: str | None = None,
    ) -> pl.DataFrame:
        return self._df.with_columns(
            _normal_expr(mean=mean, std=std, seed=seed).alias(name or "normal")
        )

    def binomial(
        self,
        n: IntParam,
        p: FloatParam,
        seed: int | None = None,
        name: str | None = None,
    ) -> pl.DataFrame:
        return self._df.with_columns(_binomial_expr(n=n, p=p, seed=seed).alias(name or "binomial"))

    def randint(
        self,
        low: IntParam = 0,
        high: IntParam = 2,
        seed: int | None = None,
        name: str | None = None,
    ) -> pl.DataFrame:
        return self._df.with_columns(
            _randint_expr(low=low, high=high, seed=seed).alias(name or "randint")
        )

lf.random — LazyFrame namespace

Same API as df.random but returns a pl.LazyFrame. Lets the random draws stay inside a lazy plan and be optimized alongside the rest of your query.

(
    df.lazy()
      .filter(pl.col("active"))
      .random.normal(seed=42, name="noise")
      .collect()
)

Null handling

When a parameter is supplied as a column or expression, any null in that column is propagated to the output as null instead of raising. Scalar parameters are validated up front (seed >= 0, 0 <= p <= 1, valid distribution params) and raise ValueError / PolarsError if invalid.