pola-rs/polars · error · ValueError

arr.dot query vector must be one-dimensional

Error message

arr.dot query vector must be one-dimensional

What it means

Expr.arr.dot computes a dot product between each sub-array and a query vector. When the vector is a numpy array, polars requires ndim == 1; a 0-d scalar array or a 2-d matrix raises ValueError before any expression is built. Python lists/tuples bypass the check.

Source

Thrown at py-polars/src/polars/expr/array.py:356

        >>> query = [2.0, 3.0]
        >>> df.select(pl.col("a").arr.dot(query))
        shape: (2, 1)
        ┌──────┐
        │ a    │
        │ ---  │
        │ f64  │
        ╞══════╡
        │ 8.0  │
        │ 18.0 │
        └──────┘
        """
        if isinstance(other, Sequence) and not isinstance(other, (str, bytes)):
            other = list(other)
            other = F.lit(other).list.to_array(len(other))
        elif _check_for_numpy(other) and isinstance(other, np.ndarray):
            if other.ndim != 1:
                msg = "arr.dot query vector must be one-dimensional"
                raise ValueError(msg)
            other = F.lit(other).implode().list.to_array(other.size)

        other_pyexpr = parse_into_expression(other)
        return wrap_expr(self._pyexpr.arr_dot(other_pyexpr))

    def std(self, ddof: int = 1) -> Expr:
        """
        Compute the std of the values of the sub-arrays.

        .. engine-support:: in-memory, streaming, distributed

        Examples
        --------
        >>> df = pl.DataFrame(
        ...     data={"a": [[1, 2], [4, 3]]},
        ...     schema={"a": pl.Array(pl.Int64, 2)},
        ... )
        >>> df.select(pl.col("a").arr.std())

View on GitHub (pinned to df599052da)

Solutions

  1. Flatten the array first: vec = vec.reshape(-1) (or vec.ravel() / vec.squeeze())
  2. Pass a Python list or tuple instead: arr.dot([1, 2, 3])
  3. Check other.ndim == 1 and that the length matches the fixed array width before calling

Example fix

# before
pl.col('vecs').arr.dot(np.load('w.npy'))  # w.npy is (1, 3): ValueError

# after
pl.col('vecs').arr.dot(np.load('w.npy').reshape(-1))
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np

if isinstance(vec, np.ndarray) and vec.ndim != 1:
    vec = vec.reshape(-1)
expr = pl.col('vecs').arr.dot(vec)

Type guard

import numpy as np
from typing import TypeGuard

def is_1d_vector(other) -> TypeGuard[np.ndarray]:
    return isinstance(other, np.ndarray) and other.ndim == 1

Prevention

When it happens

Trigger: pl.col('vecs').arr.dot(np.array([[1, 2], [3, 4]])) (2-d), arr.dot(np.array(3)) (0-d), or a (1, n) shaped row vector straight from an ML pipeline.

Common situations: Passing model weight matrices or batched (batch, n) vectors instead of a single n-vector; forgetting .ravel()/.squeeze() after loading weights from .npy files or checkpoints.

Related errors


AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16). Data as JSON: /api/errors/586cac4c44e27d5f. Report an issue: GitHub.