{"record":{"id":"5f706a65bbba6fa7","repo":"pandas-dev/pandas","slug":"only-integers-slices-ellipsis-num-5f706a","errorCode":null,"errorMessage":"only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices","messagePattern":"only integers, slices \\(`:`\\), ellipsis \\(`\\.\\.\\.`\\), numpy\\.newaxis \\(`None`\\) and integer or boolean arrays are valid indices","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/sparse/array.py","lineNumber":1093,"sourceCode":"                # should be shifted. NB: here we are careful to also not shift by a\n                # negative value for a case like [0, 1][-100:] where the start index\n                # should be treated like 0\n                if start > 0:\n                    sp_index -= start\n\n                # Length of our result should match applying this slice to a range\n                # of the length of our original array\n                new_len = len(range(len(self))[key])\n                new_sp_index = make_sparse_index(new_len, sp_index, self.kind)\n                return type(self)._simple_new(sp_vals, new_sp_index, self.dtype)\n            else:\n                indices = np.arange(len(self), dtype=np.int32)[key]\n                return self.take(indices)\n\n        elif not is_list_like(key):\n            # e.g. \"foo\" or 2.5\n            # exception message copied from numpy\n            raise IndexError(\n                r\"only integers, slices (`:`), ellipsis (`...`), numpy.newaxis \"\n                r\"(`None`) and integer or boolean arrays are valid indices\"\n            )\n\n        else:\n            if isinstance(key, SparseArray):\n                # NOTE: If we guarantee that SparseDType(bool)\n                # has only fill_value - true, false or nan\n                # (see GH PR 44955)\n                # we can apply mask very fast:\n                if is_bool_dtype(key):\n                    if isna(key.fill_value):\n                        return self.take(key.sp_index.indices[key.sp_values])\n                    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","sourceCodeStart":1075,"sourceCodeEnd":1111,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/sparse/array.py#L1075-L1111","documentation":"Raised in SparseArray.__getitem__ when the key is not an integer, not a tuple, not a slice, and not list-like (e.g. a string label or a float). SparseArray is positional-only, so label or non-integer-scalar indexing is invalid. The message is mirrored from numpy for familiarity.","triggerScenarios":"sparse_arr['foo']; sparse_arr[2.5]; passing a column label or datetime to index a SparseArray directly instead of going through the Series label index.","commonSituations":"Treating a SparseArray like a Series (.loc semantics); float indices from computations that should be int; label-based lookups forwarded to .array.","solutions":["Use integer positions: sparse_arr[int(i)].","For label access, index the Series: pd.Series(sparse_arr, index=labels)['foo'].","Coerce computed indices to int and validate they are in range."],"exampleFix":"// before\nval = sparse_arr['2020-01-01']\n// after\nval = pd.Series(sparse_arr, index=date_index)['2020-01-01']","handlingStrategy":"type-guard","validationCode":"import pandas as pd\nfrom pandas.api.types import is_integer, is_list_like\n\ndef getitem_sparse_safe(arr, key, labels=None):\n    if isinstance(key, str) or (not is_integer(key) and not is_list_like(key) and not isinstance(key, slice)):\n        if labels is None:\n            raise IndexError('positional SparseArray; cannot use label key')\n        return pd.Series(arr, index=labels)[key]\n    return arr[int(key) if is_integer(key) else key]","typeGuard":"def is_positional_key(key) -> bool:\n    from pandas.api.types import is_integer\n    import numpy as np\n    return is_integer(key) or isinstance(key, (slice, np.ndarray, list))","tryCatchPattern":"try:\n    return arr[key]\nexcept IndexError as e:\n    if 'valid indices' in str(e):\n        return pd.Series(arr, index=labels)[key]\n    raise","preventionTips":["Use integer positions for SparseArray indexing.","Do label lookups through the wrapping Series.","Coerce float indices to int before indexing."],"tags":["pandas","sparse","sparse-array","indexing","indexerror"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}