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

ExtensionArray.item() mirrors numpy.ndarray.item(): when called with no arguments it must return the single Python scalar held in a length-1 array. If len(self) != 1 the call is ambiguous (which element?), so pandas raises ValueError. This is a deliberate numpy-compatible contract, not a bug.

Solutions

  1. Verify length first: if len(arr) == 1: arr.item() — or just index explicitly with arr.item(0)/arr[0].
  2. If you expect exactly one element, guard with assert len(arr) == 1 before calling .item().
  3. If multiple elements are valid, iterate or use arr.tolist() / arr[0] instead of .item().

Example fix

// before
val = arr.item()  # ValueError if len != 1

// after
if len(arr) == 1:
    val = arr.item()
else:
    val = arr[0]  # or handle the multi-element case
Defensive patterns

Strategy: validation

Validate before calling

if len(arr) != 1:
    raise ValueError(f'expected length-1 array, got {len(arr)}')
val = arr.item()

Try / catch

try:
    val = arr.item()
except ValueError:
    val = arr[0] if len(arr) else None

Prevention

When it happens

Trigger: Calling arr.item() (no index) on an ExtensionArray of length 0 or length >= 2. Common after a reduction or filter that the caller assumed collapsed to one element but did not, e.g. arr[arr > 0].item() when multiple values match.

Common situations: Chaining .item() after a boolean filter expecting a unique hit. Calling .item() on an empty result from a query. Confusing .item() with .item(0) (the indexed form, which does not require length 1).

Related errors


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

Appendix: source

Thrown at pandas/core/arrays/base.py:677

        See Also
        --------
        numpy.ndarray.item : Return the item of an array as a scalar.

        Examples
        --------
        >>> arr = pd.array([1], dtype="Int64")
        >>> arr.item()
        np.int64(1)

        >>> arr = pd.array([1, 2, 3], dtype="Int64")
        >>> arr.item(0)
        np.int64(1)
        >>> arr.item(2)
        np.int64(3)
        """
        if index is None:
            if len(self) != 1:
                raise ValueError(
                    "can only convert an array of size 1 to a Python scalar"
                )
            return self[0]
        else:
            if not is_integer(index):
                raise TypeError(f"index must be an integer, got {type(index)}")
            return self[index]

    def to_numpy(
        self,
        dtype: npt.DTypeLike | None = None,
        copy: bool = False,
        na_value: object = lib.no_default,
    ) -> np.ndarray:
        """
        Convert to a NumPy ndarray.

        This is similar to :meth:`numpy.asarray`, but may provide additional control

View on GitHub (pinned to 3b7651241d)