pola-rs/polars · error · ValueError
cannot specify both `n` and `fraction`
Error message
cannot specify both `n` and `fraction`
What it means
Expr.sample rejects sampling by count and by proportion at the same time: `n` (absolute number of rows) and `fraction` (0..1 proportion) are mutually exclusive and dispatch to different Rust kernels (sample_n vs sample_frac). Passing both is ambiguous, so the Python layer raises ValueError immediately.
Source
Thrown at py-polars/src/polars/expr/expr.py:11034
>>> df.select(
... pl.col("a").sample(
... fraction=1.0, with_replacement=True, shuffle=False, seed=1
... )
... )
shape: (3, 1)
┌─────┐
│ a │
│ --- │
│ i64 │
╞═════╡
│ 3 │
│ 3 │
│ 1 │
└─────┘
"""
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.sample_frac(
fraction_pyexpr, with_replacement, shuffle, seed
)
)
if n is None:
n = 1
n_pyexpr = parse_into_expression(n)
return wrap_expr(
self._pyexpr.sample_n(n_pyexpr, with_replacement, shuffle, seed)
)
@deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0")
def ewm_mean(View on GitHub (pinned to df599052da)
Solutions
- Pick one: sample(n=10) for a fixed count or sample(fraction=0.5) for a proportion.
- If you ported from pandas, translate frac= to fraction= and delete n.
- To cap a proportional sample, compute the desired count yourself and pass only n.
Example fix
# before
pl.col('a').sample(n=10, fraction=0.5, with_replacement=True)
# after
pl.col('a').sample(n=10, with_replacement=True) Defensive patterns
Strategy: validation
Validate before calling
assert (n is None) != (fraction is None), 'sample: pass exactly one of n / fraction'
Prevention
- When porting pandas code, remember pandas frac has no direct two-argument equivalent in polars.
- Model sampling config as a single discriminated choice (either count or fraction), never two optional fields.
When it happens
Trigger: pl.col('a').sample(n=10, fraction=0.5), or sample(n, frac) style ported from pandas where both were accepted.
Common situations: Porting pandas df.sample(n=..., frac=...) code — pandas allows frac plus n as an upper bound, polars does not; config-driven sampling where both knobs exist and someone enables both.
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/5d7a7b2a014bd7bf.
Report an issue: GitHub.