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 ExtensionArray.item(index=None) when index is None and the array length is not exactly 1. This mirrors numpy.ndarray.item(): with no index, only a single-element array can be converted to a scalar. Multi-element (or empty) arrays raise ValueError. Reached through pd.array(...).item() or Series.array.item().
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 controlView on GitHub (pinned to 71959b8cb9)
Solutions
- Pass an explicit index: `arr.item(0)` to get the first element regardless of length.
- Ensure the array has exactly one element before calling item(): filter/slice first, e.g. `s[s>0].array.item()` only when unique.
- Use `arr[0]` / `s.iloc[0]` if you just want the first value without the size-1 constraint.
- Check `len(arr) == 1` before calling item() to give a clearer error to callers.
Example fix
# before arr = pd.array([1, 2, 3], dtype="Int64") arr.item() # ValueError: can only convert an array of size 1 # after arr.item(0) # explicit index # or single = pd.array([7], dtype="Int64") single.item()
Defensive patterns
Strategy: validation
Validate before calling
def safe_item(arr, index=None):
if index is None and len(arr) != 1:
raise ValueError(f"len(arr)={len(arr)}; pass an explicit index or ensure exactly one element")
return arr.item(index) Type guard
def is_single_element(arr) -> bool:
return len(arr) == 1 Try / catch
try:
return arr.item()
except ValueError as e:
if "size 1" in str(e):
return arr.item(0)
raise Prevention
- Pass an explicit index when you want a specific element regardless of length.
- Check len(arr)==1 before scalar conversion in reductions.
- Use arr[0]/s.iloc[0] when uniqueness is not guaranteed.
When it happens
Trigger: Calling `arr.item()` on an extension array with 0 or 2+ elements. Common after reductions/groupby that should return one value but unexpectedly return many (or none).
Common situations: Aggregations expected to yield a scalar; extracting a single config value from a filtered Series; asserting uniqueness of a query result.
Related errors
- cannot diff {type(arr).__name__} on axis={axis}
- Encountered an NA value with skipna=False
- No such keys(s): {pat!r}
- {k} is not a valid identifier
- {k} is a python keyword
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/3aeb83773f1172dc.
Report an issue: GitHub.