{"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":1125,"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":1107,"sourceCodeEnd":1143,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/sparse/array.py#L1107-L1143","documentation":"Raised inside SparseArray.__getitem__ when the indexer is a list-like object that is not a boolean mask, not a SparseArray, and critically has no __len__ (e.g. a 0-dimensional numpy array). The slice dispatcher falls through every recognized branch and refuses to guess how to index the sparse storage with such a key. This protects the sp_index invariant from being corrupted by an ambiguous key.","triggerScenarios":"Calling sparse_arr[key] where key is a numpy 0-d array (e.g. np.array(2)), a masked/odd object whose __len__ was stripped, or a pandas scalar wrapper passed positionally. Also reachable via Series.iloc on a sparse-backed Series with an object-dtype 0-d indexer.","commonSituations":"Programmatically building an indexer and accidentally reducing it to 0-d (np.array(arr)[()] patterns), passing a DataFrame cell value (which may be 0-d) as an index, or passing a pandas Timestamp/NaT-like scalar where an integer was expected.","solutions":["Wrap the key so it is a 1-d integer array: sparse_arr[np.atleast_1d(key)] or sparse_arr[int(key)].","If you meant scalar access, call sparse_arr._get_val_at(int(key)) or use a Series and .iloc[int(key)].","If key should be a boolean mask, ensure it is np.asarray(mask) with ndim==1 before indexing."],"exampleFix":"// before\nkey = np.array(2)\nval = sparse_arr[key]  # raises 'Cannot slice with ...'\n\n// after\nval = sparse_arr[int(key)]","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef as_sparse_indexer(key):\n    arr = np.asarray(key)\n    if arr.ndim == 0:\n        return int(arr)\n    return arr\n\n# usage:\n# key = as_sparse_indexer(user_key)\n# val = sparse_arr[key]","typeGuard":"import numpy as np\n\ndef is_valid_sparse_indexer(key) -> bool:\n    if isinstance(key, slice):\n        return True\n    arr = np.asarray(key)\n    return arr.ndim == 1 or np.isscalar(key)","tryCatchPattern":"try:\n    val = sparse_arr[key]\nexcept ValueError as e:\n    if 'Cannot slice with' in str(e):\n        val = sparse_arr[int(np.asarray(key))]\n    else:\n        raise","preventionTips":["Always wrap programmatically-built indexers with np.atleast_1d before passing to []","Use Series.iloc[int(pos)] for scalar positional access instead of raw SparseArray indexing","Assert indexer dimensionality at API boundaries"],"tags":["sparse","indexing","getitem"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}