{"record":{"id":"b12498609cecc8da","repo":"pandas-dev/pandas","slug":"indices-must-be-an-array-not-a-scalar-indices","errorCode":null,"errorMessage":"'indices' must be an array, not a scalar '{indices}'.","messagePattern":"'indices' must be an array, not a scalar '(.+?)'\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/sparse/array.py","lineNumber":1149,"sourceCode":"        if loc < 0:\n            loc += n\n\n        if loc >= n or loc < 0:\n            raise IndexError(\n                f\"index is out of bounds: must be an integer between -{n} and {n - 1}\"\n            )\n\n        sp_loc = self.sp_index.lookup(loc)\n        if sp_loc == -1:\n            return self.fill_value\n        else:\n            val = self.sp_values[sp_loc]\n            val = maybe_box_datetimelike(val, self.sp_values.dtype)\n            return val\n\n    def take(self, indices, *, allow_fill: bool = False, fill_value=None) -> Self:\n        if is_scalar(indices):\n            raise ValueError(f\"'indices' must be an array, not a scalar '{indices}'.\")\n        indices = np.asarray(indices, dtype=np.int32)\n\n        dtype = None\n        if indices.size == 0:\n            result = np.array([], dtype=\"object\")\n            dtype = self.dtype\n        elif allow_fill:\n            result = self._take_with_fill(indices, fill_value=fill_value)\n        else:\n            return self._take_without_fill(indices)\n\n        return type(self)(\n            result, fill_value=self.fill_value, kind=self.kind, dtype=dtype\n        )\n\n    def _take_with_fill(self, indices, fill_value=None) -> np.ndarray:\n        if fill_value is None:\n            fill_value = self.dtype.na_value","sourceCodeStart":1131,"sourceCodeEnd":1167,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/sparse/array.py#L1131-L1167","documentation":"Raised by SparseArray.take when the `indices` argument is a Python/numpy scalar. The take protocol (NEP 29 / ExtensionArray.take) requires a 1-d array of positions because it must build a new SparseArray of the same length as indices; a single scalar has no length to drive that. Pandas raises explicitly rather than letting np.asarray produce a 0-d array that later fails confusingly.","triggerScenarios":"Calling sparse_arr.take(2), pd.api.extensions.take(arr, 5), or sparse_arr[[2]] where the list was collapsed to a scalar by upstream code. Also from .reindex internals that hand a scalar indexer to take.","commonSituations":"Mixing scalar .iloc[pos] expectations with the .take API, or writing helper functions that accept 'index or indices' and forward the value unchanged to take.","solutions":["Pass a 1-d array: sparse_arr.take([2]) or sparse_arr.take(np.array([2], dtype=np.int32)).","For single-position access use sparse_arr._get_val_at(int(idx)) or wrap the array in a Series and use .iloc[int(idx)].","Normalize at the boundary: idx = np.atleast_1d(np.asarray(idx, dtype=np.int32)) before calling take."],"exampleFix":"// before\nval = sparse_arr.take(3)  # raises 'indices must be an array'\n\n// after\nval = sparse_arr.take([3])","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef take_safe(arr, indices):\n    idx = np.atleast_1d(np.asarray(indices, dtype=np.int32))\n    return arr.take(idx)","typeGuard":"import numpy as np\n\ndef is_array_indices(indices) -> bool:\n    return hasattr(indices, '__len__') or np.asarray(indices).ndim >= 1","tryCatchPattern":"try:\n    out = arr.take(indices)\nexcept ValueError as e:\n    if 'must be an array' in str(e):\n        out = arr.take([int(indices)])\n    else:\n        raise","preventionTips":["Always pass 1-d arrays to SparseArray.take, never bare scalars","Wrap helper functions that accept 'index or indices' with np.atleast_1d","Prefer Series.iloc[pos] for single-position reads"],"tags":["sparse","take","scalar","indexing"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}