pola-rs/polars · error · ValueError

cannot specify both `n` and `fraction`

Error message

cannot specify both `n` and `fraction`

What it means

Parameter-exclusivity error from list.sample: the sample size can be specified either as an absolute count (`n`) or as a relative `fraction` of the list, never both. Supplying both makes the intended sample size ambiguous, so the guard rejects the call before any sampling happens.

Solutions

  1. Pass only n OR only fraction, setting the other to None
  2. Compute n from fraction at the call site if you know the list length
  3. Normalize in wrapper code: if fraction is not None: use fraction else use n
  4. Validate config so exactly one of count/percentage is set

Example fix

// before
pl.col('l').list.sample(n=2, fraction=0.5)
// after
pl.col('l').list.sample(fraction=0.5)
Defensive patterns

Strategy: validation

Validate before calling

if (n is not None) == (fraction is not None):
    raise ValueError('specify exactly one of n or fraction')

Try / catch

try:
    e = col.list.sample(n=n, fraction=fraction)
except ValueError as e:
    if 'both `n` and `fraction`' in str(e):
        e = col.list.sample(n=n if n is not None else None,
                            fraction=None if n is not None else fraction)
    else:
        raise

Prevention

When it happens

Trigger: Calling pl.col('l').list.sample(n=2, fraction=0.5) with both arguments non-None; calling sample(2, 0.5) positionally.

Common situations: Config exposing both 'count' and 'percentage' fields that are both set; copying a call and adding a fraction without removing n; generic wrapper functions forwarding both options.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/bfba474f00de5362. Report an issue: GitHub.

Appendix: source

Thrown at py-polars/src/polars/expr/list.py:248

        >>> 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 fe841f959e)