{"record":{"id":"e48b10afdf023475","repo":"pandas-dev/pandas","slug":"can-only-convert-an-array-of-size-1-to-a-python-sc-e48b10","errorCode":null,"errorMessage":"can only convert an array of size 1 to a Python scalar","messagePattern":"can only convert an array of size 1 to a Python scalar","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/base.py","lineNumber":438,"sourceCode":"        --------\n        Index.values : Returns an array representing the data in the Index.\n        Series.head : Returns the first `n` rows.\n\n        Examples\n        --------\n        >>> s = pd.Series([1])\n        >>> s.item()\n        1\n\n        For an index:\n\n        >>> s = pd.Series([1], index=[\"a\"])\n        >>> s.index.item()\n        'a'\n        \"\"\"\n        if len(self) == 1:\n            return next(iter(self))\n        raise ValueError(\"can only convert an array of size 1 to a Python scalar\")\n\n    @property\n    def nbytes(self) -> int:\n        \"\"\"\n        Return the number of bytes in the underlying data.\n\n        Includes only the memory used by the array values; overhead such as\n        the index is not included. Useful for estimating memory usage.\n\n        See Also\n        --------\n        Series.ndim : Number of dimensions of the underlying data.\n        Series.size : Return the number of elements in the underlying data.\n\n        Examples\n        --------\n        For Series:\n","sourceCodeStart":420,"sourceCodeEnd":456,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/base.py#L420-L456","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Check len(s) == 1 before calling .item().","If you want the first element regardless, use s.iloc[0] instead.","If empty is valid, guard with if len(s): ... else default.","If multiple are expected, aggregate first (s.sum(), s.iloc[0]) or use .tolist()."],"exampleFix":"// before\nval = df.query('id == @target')['amount'].item()\n// after\nsub = df.query('id == @target')['amount']\nif len(sub) != 1:\n    raise ValueError(f'expected one row, got {len(sub)}')\nval = sub.item()","handlingStrategy":"validation","validationCode":"if len(s) != 1:\n    raise ValueError(f'expected 1 element, got {len(s)}')\nval = s.item()","typeGuard":"def exactly_one(s) -> bool:\n    return len(s) == 1","tryCatchPattern":"try:\n    val = s.item()\nexcept ValueError:\n    # fall back to first or report\n    val = s.iloc[0] if len(s) else None","preventionTips":["Always assert cardinality before .item().","Prefer .iloc[0] when 'first' is acceptable.","Treat empty results as a separate case rather than relying on .item()."],"tags":["value-error","item","series","index","cardinality"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}