pola-rs/polars · error · ValueError
cannot specify both `n` and `fraction`
Error message
cannot specify both `n` and `fraction`
What it means
The list namespace's Expr.list.sample mirrors the frame/expr sampler: `n` (items to draw per sub-list) and `fraction` (proportion per sub-list) are mutually exclusive and route to different Rust kernels (list_sample_n vs list_sample_fraction). Supplying both is ambiguous and rejected in the Python layer with ValueError.
Source
Thrown at py-polars/src/polars/expr/list.py:253
>>> df = pl.DataFrame({"values": [[1, 2, 3], [4, 5]], "n": [2, 1]})
>>> df.with_columns(
... sample=pl.col("values").list.sample(
... n=pl.col("n"), shuffle=False, seed=1
... )
... )
shape: (2, 3)
┌───────────┬─────┬───────────┐
│ values ┆ n ┆ sample │
│ --- ┆ --- ┆ --- │
│ list[i64] ┆ i64 ┆ list[i64] │
╞═══════════╪═════╪═══════════╡
│ [1, 2, 3] ┆ 2 ┆ [2, 3] │
│ [4, 5] ┆ 1 ┆ [5] │
└───────────┴─────┴───────────┘
"""
if n is not None and fraction is not None:
msg = "cannot specify both `n` and `fraction`"
raise ValueError(msg)
if fraction is not None:
fraction_pyexpr = parse_into_expression(fraction)
return wrap_expr(
self._pyexpr.list_sample_fraction(
fraction_pyexpr, with_replacement, shuffle, seed
)
)
if n is None:
n = 1
n_pyexpr = parse_into_expression(n)
return wrap_expr(
self._pyexpr.list_sample_n(n_pyexpr, with_replacement, shuffle, seed)
)
def sum(self) -> Expr:
"""View on GitHub (pinned to df599052da)
Solutions
- Keep one argument: list.sample(n=2) or list.sample(fraction=0.5).
- Delete the redundant argument from shared config before forwarding.
Example fix
# before
pl.col('vals').list.sample(n=2, fraction=0.5)
# after
pl.col('vals').list.sample(n=2) Defensive patterns
Strategy: validation
Validate before calling
assert (n is None) != (fraction is None), 'list.sample: pass exactly one of n / fraction'
Prevention
- Same exclusivity rule as Expr.sample and DataFrame.sample — one sampling mode per call.
- Store sampling config as ('n', value) or ('fraction', value), not two optional fields.
When it happens
Trigger: pl.col('vals').list.sample(n=2, fraction=0.5); also df.select(pl.col('l').list.sample(2, 0.5)) positional form.
Common situations: Sampling config with both knobs; adapting Expr.sample code to per-list sampling and keeping both arguments; pandas-derived habits where n and frac coexist.
Related errors
- cannot specify both `n` and `fraction`
- cannot specify both `value` and `strategy`
- must specify either a fill `value` or `strategy`
- strategy {strategy!r} is not supported
- reinterpret requires exactly one of `signed` or `dtype` to b
AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16).
Data as JSON: /api/errors/bfba474f00de5362.
Report an issue: GitHub.