pandas-dev/pandas · error · ValueError

can only convert an array of size 1 to a Python scalar

Error message

can only convert an array of size 1 to a Python scalar

What it means

Raised by PandasObject.item() when the object's length is not exactly 1. Mirrors numpy's item() contract: only single-element containers can be reduced to a Python scalar. Calling on empty or multi-element Series/Index raises ValueError.

Source

Thrown at pandas/core/base.py:438

        --------
        Index.values : Returns an array representing the data in the Index.
        Series.head : Returns the first `n` rows.

        Examples
        --------
        >>> s = pd.Series([1])
        >>> s.item()
        1

        For an index:

        >>> s = pd.Series([1], index=["a"])
        >>> s.index.item()
        'a'
        """
        if len(self) == 1:
            return next(iter(self))
        raise ValueError("can only convert an array of size 1 to a Python scalar")

    @property
    def nbytes(self) -> int:
        """
        Return the number of bytes in the underlying data.

        Includes only the memory used by the array values; overhead such as
        the index is not included. Useful for estimating memory usage.

        See Also
        --------
        Series.ndim : Number of dimensions of the underlying data.
        Series.size : Return the number of elements in the underlying data.

        Examples
        --------
        For Series:

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Check len(s) == 1 before calling .item().
  2. Use .iloc[0] if you want the first element regardless of count.
  3. Handle empty/multi cases explicitly with conditional logic.

Example fix

// before
v = df.loc[df.id == q, 'name'].item()

// after
sub = df.loc[df.id == q, 'name']
v = sub.item() if len(sub) == 1 else sub.iloc[0]
Defensive patterns

Strategy: validation

Validate before calling

if len(s) != 1:
    raise ValueError(f'expected size 1, got {len(s)}')

Type guard

def is_single_element(s) -> bool:
    return len(s) == 1

Try / catch

try:
    v = s.item()
except ValueError as e:
    if 'size 1' in str(e):
        v = s.iloc[0] if len(s) else None
    else:
        raise

Prevention

When it happens

Trigger: `df['x'].item()` where len != 1; `s.index.item()` on multi-row data; common after aggregations that unexpectedly return >1 row.

Common situations: Asserting 'exactly one match' in queries; using .item() to unpack instead of .iloc[0]; empty results from filters.

Related errors


AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07). Data as JSON: /api/errors/e48b10afdf023475. Report an issue: GitHub.