pola-rs/polars · error · ShapeError

Series length mismatch: expected

Error message

Series length mismatch: expected {n!r}, found {m!r}

What it means

Raised when a binary Series operation (here `Series.dot`, and the same message is reused in DataFrame construction helpers) receives a Series/sequence whose length differs from the receiver's. Polars requires positional alignment between operands, so mismatched lengths cannot be evaluated element-wise.

Solutions

  1. Check len(a) == len(b) before the operation and trim or pad the shorter operand.
  2. Re-derive the second Series from the same filtered/sliced source so both share indices.
  3. If an intentional broadcast is meant, use pl.lit(value) / Expr broadcasting instead of Series-to-Series.

Example fix

# before
weights = pl.Series([0.1, 0.2])
result = values.dot(weights)  # ShapeError

# after
weights = pl.Series([0.1, 0.2, 0.3])
assert len(weights) == len(values)
result = values.dot(weights)
Defensive patterns

Strategy: validation

Validate before calling

if len(values) != len(weights):
    raise ValueError(f"length mismatch: {len(values)} vs {len(weights)}")
result = values.dot(weights)

Type guard

def same_length(a, b) -> bool:
    return len(a) == len(b)

Prevention

When it happens

Trigger: Calling s.dot(other) where len(other) != len(self); passing dict/list columns of unequal lengths to DataFrame(...) via dict_to_pydf or _handle_columns_arg; supplying nested sequences whose inner lengths disagree.

Common situations: Computing a dot product against a weight vector of the wrong size; building a DataFrame from dict values where one list has extra/missing rows after a filtered slice; off-by-one after dropping rows from one column only.

Related errors


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

Appendix: source

Thrown at py-polars/src/polars/series/series.py:5925

        Examples
        --------
        >>> s = pl.Series("a", [1, 2, 3])
        >>> s2 = pl.Series("b", [4.0, 5.0, 6.0])
        >>> s.dot(s2)
        32.0

        Parameters
        ----------
        other
            Series (or array) to compute dot product with.
        """
        if not isinstance(other, Series):
            other = Series(other)
        if len(self) != len(other):
            n, m = len(self), len(other)
            msg = f"Series length mismatch: expected {n!r}, found {m!r}"
            raise ShapeError(msg)
        return self._s.dot(other._s)

    def mode(self, *, maintain_order: bool = False) -> Series:
        """
        Compute the most occurring value(s).

        Can return multiple Values.

        Parameters
        ----------
        maintain_order
            Maintain order of data. This requires more work.

        Examples
        --------
        >>> s = pl.Series("a", [1, 2, 2, 3])
        >>> s.mode()
        shape: (1,)

View on GitHub (pinned to fe841f959e)