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 IndexOpsMixin.item() when len(self) != 1. The .item() contract is to return the single Python scalar held by a length-1 Series or Index; it is the pandas analogue of extracting the only element. Any other length (0 or >1) is a programmer error rather than a runtime edge case, so it raises ValueError unconditionally.

Solutions

  1. Check len(s) == 1 before calling .item().
  2. If you want the first element regardless, use s.iloc[0] instead.
  3. If empty is valid, guard with if len(s): ... else default.
  4. If multiple are expected, aggregate first (s.sum(), s.iloc[0]) or use .tolist().

Example fix

// before
val = df.query('id == @target')['amount'].item()
// after
sub = df.query('id == @target')['amount']
if len(sub) != 1:
    raise ValueError(f'expected one row, got {len(sub)}')
val = sub.item()
Defensive patterns

Strategy: validation

Validate before calling

if len(s) != 1:
    raise ValueError(f'expected 1 element, got {len(s)}')
val = s.item()

Type guard

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

Try / catch

try:
    val = s.item()
except ValueError:
    # fall back to first or report
    val = s.iloc[0] if len(s) else None

Prevention

When it happens

Trigger: Calling s.item() on an empty Series; calling .item() on a multi-element result from .unique(), .value_counts(), .nlargest(), or a filter that returned more than one row; chaining .item() after .groupby().first() that did not reduce to one row.

Common situations: Asserting 'exactly one row matched' after a filter; unwrapping a scalar from a groupby/aggregation that unexpectedly produced 0 or N>1 rows; testing code where the fixture has multiple rows.

Related errors


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

Appendix: 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 3b7651241d)