pandas-dev/pandas · error · ValueError

Cannot slice with '{key}'

Error message

Cannot slice with '{key}'

What it means

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.

Source

Thrown at pandas/core/arrays/sparse/array.py:1125

                    if not key.fill_value:
                        return self.take(key.sp_index.indices)
                    n = len(self)
                    mask = np.full(n, True, dtype=np.bool_)
                    mask[key.sp_index.indices] = False
                    return self.take(np.arange(n)[mask])
                else:
                    key = np.asarray(key)

            key = check_array_indexer(self, key)

            if com.is_bool_indexer(key):
                # mypy doesn't know we have an array here
                key = cast("np.ndarray", key)
                return self.take(np.arange(len(key), dtype=np.int32)[key])
            elif hasattr(key, "__len__"):
                return self.take(key)
            else:
                raise ValueError(f"Cannot slice with '{key}'")

        return type(self)(data_slice, kind=self.kind)

    def _get_val_at(self, loc):
        n = len(self)
        if loc < 0:
            loc += n

        if loc >= n or loc < 0:
            raise IndexError(
                f"index is out of bounds: must be an integer between -{n} and {n - 1}"
            )

        sp_loc = self.sp_index.lookup(loc)
        if sp_loc == -1:
            return self.fill_value
        else:
            val = self.sp_values[sp_loc]

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Wrap the key so it is a 1-d integer array: sparse_arr[np.atleast_1d(key)] or sparse_arr[int(key)].
  2. If you meant scalar access, call sparse_arr._get_val_at(int(key)) or use a Series and .iloc[int(key)].
  3. If key should be a boolean mask, ensure it is np.asarray(mask) with ndim==1 before indexing.

Example fix

// before
key = np.array(2)
val = sparse_arr[key]  # raises 'Cannot slice with ...'

// after
val = sparse_arr[int(key)]
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np

def as_sparse_indexer(key):
    arr = np.asarray(key)
    if arr.ndim == 0:
        return int(arr)
    return arr

# usage:
# key = as_sparse_indexer(user_key)
# val = sparse_arr[key]

Type guard

import numpy as np

def is_valid_sparse_indexer(key) -> bool:
    if isinstance(key, slice):
        return True
    arr = np.asarray(key)
    return arr.ndim == 1 or np.isscalar(key)

Try / catch

try:
    val = sparse_arr[key]
except ValueError as e:
    if 'Cannot slice with' in str(e):
        val = sparse_arr[int(np.asarray(key))]
    else:
        raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07). Data as JSON: /api/errors/c001156511bc3a5f. Report an issue: GitHub.