{"record":{"id":"c001156511bc3a5f","repo":"pandas-dev/pandas","slug":"cannot-slice-with-key","errorCode":null,"errorMessage":"Cannot slice with '{key}'","messagePattern":"Cannot slice with '(.+?)'","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/sparse/array.py","lineNumber":1130,"sourceCode":"                    if not key.fill_value:\n                        return self.take(key.sp_index.indices)\n                    n = len(self)\n                    mask = np.full(n, True, dtype=np.bool_)\n                    mask[key.sp_index.indices] = False\n                    return self.take(np.arange(n)[mask])\n                else:\n                    key = np.asarray(key)\n\n            key = check_array_indexer(self, key)\n\n            if com.is_bool_indexer(key):\n                # mypy doesn't know we have an array here\n                key = cast(\"np.ndarray\", key)\n                return self.take(np.arange(len(key), dtype=np.int32)[key])\n            elif hasattr(key, \"__len__\"):\n                return self.take(key)\n            else:\n                raise ValueError(f\"Cannot slice with '{key}'\")\n\n        return type(self)(data_slice, kind=self.kind)\n\n    def _get_val_at(self, loc):\n        n = len(self)\n        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]","sourceCodeStart":1112,"sourceCodeEnd":1148,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/sparse/array.py#L1112-L1148","documentation":"ValueError raised at the tail of SparseArray.__getitem__ when the normalized key lacks __len__ and is not a recognized scalar/slice type, so the array cannot decide between take and slice semantics.","triggerScenarios":"Passing an exotic indexable (e.g. a 0-d object, a custom type) that survives earlier branches but exposes neither boolean indexing nor __len__.","commonSituations":"Custom index types passed to a SparseArray; pandas internals forwarding unexpected key objects.","solutions":["Convert the key to a concrete array via np.asarray(key) before indexing.","Use arr.take(indices) explicitly with an integer array.","Simplify to a slice or integer key."],"exampleFix":"// before\narr[my_custom_key]  # raises\n// after\narr[np.asarray(my_custom_key)]","handlingStrategy":"validation","validationCode":"import numpy as np\ndef normalize_key(key):\n    return np.asarray(key) if not hasattr(key, '__len__') and not isinstance(key, slice) else key","typeGuard":"def key_is_indexable(key) -> bool:\n    return isinstance(key, slice) or hasattr(key, '__len__') or isinstance(key, int)","tryCatchPattern":"try:\n    arr[key]\nexcept ValueError as e:\n    if \"Cannot slice with\" in str(e):\n        out = arr[np.asarray(key)]\n    else:\n        raise","preventionTips":["Convert custom keys to numpy arrays before indexing.","Prefer take() with explicit integer arrays for exotic selectors."],"tags":["sparse","indexing","getitem","validation"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}