pola-rs/polars · error
cannot specify both `n` and `fraction`
Error message
cannot specify both `n` and `fraction`
What it means
DataFrame.sample draws rows either by absolute count (`n`) or by a fraction of rows (`fraction`); the two parameters are mutually exclusive and both default to None. Passing non-None values for both raises ValueError immediately, before any sampling happens, because the intended sample size would be ambiguous.
Source
Thrown at py-polars/src/polars/dataframe/frame.py:11653
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.sample(n=2, shuffle=False, seed=0) # doctest: +IGNORE_RESULT
shape: (2, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 3 ┆ 8 ┆ c │
│ 2 ┆ 7 ┆ b │
└─────┴─────┴─────┘
"""
if n is not None and fraction is not None:
msg = "cannot specify both `n` and `fraction`"
raise ValueError(msg)
if n is None and fraction is not None:
if not isinstance(fraction, pl.Series):
fraction = pl.Series("frac", [fraction])
return self._from_pydf(
self._df.sample_frac(fraction._s, with_replacement, shuffle, seed)
)
if n is None:
n = 1
if not isinstance(n, pl.Series):
n = pl.Series("", [n])
return self._from_pydf(self._df.sample_n(n._s, with_replacement, shuffle, seed))
def fold(self, operation: Callable[[Series, Series], Series]) -> Series:View on GitHub (pinned to df599052da)
Solutions
- Pass exactly one of n or fraction and leave the other as None (or omit it)
- In wrappers, resolve the conflict first: use fraction if frac is not None else n
- When splatting option dicts, drop the unused key: opts.pop('n', None) or opts.pop('fraction', None)
Example fix
# before sampled = df.sample(n=100, fraction=0.1) # after sampled = df.sample(n=100) # or sampled = df.sample(fraction=0.1)
Defensive patterns
Strategy: validation
Validate before calling
if n is not None and fraction is not None:
raise ValueError('pass exactly one of n / fraction')
sampled = df.sample(n=n, fraction=fraction) Prevention
- In sampling wrappers, default both to None and resolve to exactly one before calling
- Prefer fraction for proportional sampling and n for absolute — do not expose both as non-None defaults
- When splatting option dicts, pop the key you are not using
When it happens
Trigger: df.sample(n=10, fraction=0.5); generic wrappers that expose both knobs and forward both, e.g. def take(df, n=5, frac=0.2): return df.sample(n=n, fraction=frac); refactor added fraction but left the n call site in place.
Common situations: Reusable sampling helpers with defaulted n and fraction parameters that are both non-None at the call site; A/B experiment code switching between count-based and ratio-based sampling; splatting an options dict containing both keys.
Related errors
- cannot set both 'index' and 'by_predicate'; mutually exclusi
- invalid `return_type`; found {return_type!r}, expected one o
- `offset` input for `with_row_index` cannot be {issue}, got {
- cannot use `partition_by` with `maintain_order=False, includ
- unexpected input for `strategy`: {strategy!r} Choose one of
AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16).
Data as JSON: /api/errors/88c09c76c49a1341.
Report an issue: GitHub.