pola-rs/polars · error · ValueError

can only call `.item()` without "row" or "column" values if

Error message

can only call `.item()` without "row" or "column" values if the DataFrame has a single element; shape={self.shape!r}

What it means

Raised by DataFrame.item() when called with no arguments on a frame whose shape is not exactly (1, 1). `.item()` is the numpy/antigravity-style accessor for 'the single element of this frame'; polars validates the shape up front because the return value is ambiguous for any other shape. The message includes the actual shape so you can immediately see whether you have too many rows or too many columns.

Source

Thrown at py-polars/src/polars/dataframe/frame.py:1733

        the shape is (1,1). With row/col, this is equivalent to `df[row,col]`.

        Examples
        --------
        >>> df = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
        >>> df.select((pl.col("a") * pl.col("b")).sum()).item()
        32
        >>> df.item(1, 1)
        5
        >>> df.item(2, "b")
        6
        """
        if row is None and column is None:
            if self.shape != (1, 1):
                msg = (
                    'can only call `.item()` without "row" or "column" values if the '
                    f"DataFrame has a single element; shape={self.shape!r}"
                )
                raise ValueError(msg)
            return self._df.to_series(0).get_index(0)

        elif row is None or column is None:
            msg = "cannot call `.item()` with only one of `row` or `column`"
            raise ValueError(msg)

        s = (
            self._df.to_series(column)
            if isinstance(column, int)
            else self._df.get_column(column)
        )
        return s.get_index_signed(row)

    @deprecate_renamed_parameter("future", "compat_level", version="1.1")
    def to_arrow(self, *, compat_level: CompatLevel | None = None) -> pa.Table:
        """
        Collect the underlying arrow arrays in an Arrow Table.

View on GitHub (pinned to df599052da)

Solutions

  1. Check the shape before calling: `if df.shape == (1, 1): v = df.item()`
  2. Get the first element regardless of row count: `df[0, 0]`, `df.item(0, 0)`, or `df.row(0, named=True)`
  3. Fix the upstream query so it provably returns one row: add `.filter(...)`, use `.unique()` on the grouping key, or assert row count with `pl.assert_frame`
  4. For a 1xN frame use `df.row(0)` to get all values of the single row

Example fix

# before
value = df.filter(pl.col('k') == key).select('v').item()

# after
sub = df.filter(pl.col('k') == key).select('v')
value = sub.item(0, 0) if sub.height == 1 else None
Defensive patterns

Strategy: validation

Validate before calling

if df.shape != (1, 1):
    raise ValueError(f'expected single-cell frame, got {df.shape}')
value = df.item()

Type guard

def is_single_cell(df: pl.DataFrame) -> bool:
    """True only for a 1x1 frame, the sole valid target of .item()."""
    return df.shape == (1, 1)

Try / catch

try:
    v = df.item()
except ValueError as e:
    if 'single element' in str(e):
        v = df.item(0, 0)  # or handle multi-row case explicitly
    else:
        raise

Prevention

When it happens

Trigger: `df.item()` on a 3x1 frame (e.g. a group_by().count() result that didn't reduce to one row), on a 1x2 frame, or on an empty frame. Any `.item()` without row/column arguments where `df.shape != (1, 1)`.

Common situations: Aggregations expected to return one row but returning many (e.g. forgot to filter, or group_by produced multiple groups); unique-count checks like `df.filter(...).select(pl.len()).item()` that unexpectedly yield 0 rows; reading config/lookup tables where duplicates or zero matches break the 1x1 assumption.

Related errors


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