pandas-dev/pandas · error · NotImplementedError
SparseArray does not support in-place sort
Error message
SparseArray does not support in-place sort
What it means
SparseArray.sort() is declared to satisfy the ExtensionArray/NDArrayLike sort interface but always raises NotImplementedError. Sorting a sparse layout in place would be O(n) in the dense size and invalidate the sparse index, so it is intentionally unsupported.
Solutions
- Sort the dense equivalent: sorted_vals = np.sort(np.asarray(arr)); rebuild SparseArray if needed.
- Use pd.Series(arr).sort_values().values to get an ordered sparse-backed Series.
- Guard callers with isinstance(arr, SparseArray) and route to a dense sort path.
Example fix
// before arr.sort() # raises NotImplementedError // after ordered = pd.Series(arr).sort_values() arr = pd.arrays.SparseArray(ordered.to_numpy())
Defensive patterns
Strategy: type-guard
Validate before calling
from pandas.core.arrays.sparse import SparseArray
def safe_sort(arr, **kw):
if isinstance(arr, SparseArray):
import numpy as np
return pd.arrays.SparseArray(np.sort(np.asarray(arr)))
return np.sort(arr, **kw) if hasattr(arr, 'sort') else sorted(arr) Type guard
def needs_dense_sort(arr) -> bool:
from pandas.core.arrays.sparse import SparseArray
return isinstance(arr, SparseArray) Try / catch
try:
arr.sort()
except NotImplementedError as e:
if "in-place sort" in str(e):
import numpy as np
arr = pd.arrays.SparseArray(np.sort(np.asarray(arr)))
else:
raise Prevention
- Sort sparse data via Series.sort_values or np.sort on dense materialization.
- Guard generic sort helpers with isinstance checks for SparseArray.
When it happens
Trigger: Calling arr.sort(...) directly on a SparseArray, or code that dispatches np.ndarray-style sort to an ExtensionArray (some groupby/sort_values internals).
Common situations: Generic helper code that calls .sort() on any array-like; switching a pipeline from numpy arrays to SparseArray expecting the same sort API.
Related errors
- cannot perform with type
- cannot perform with type
- Default 'empty' implementation is invalid for dtype=
- {dtype}
- function is not implemented for this dtype
AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11).
Data as JSON: /api/errors/b4736fa7079a3734.
Report an issue: GitHub.
Appendix: source
Thrown at pandas/core/arrays/sparse/array.py:630
return out
def __setitem__(self, key, value) -> None:
if self._readonly:
raise ValueError("Cannot modify read-only array")
# I suppose we could allow setting of non-fill_value elements.
# TODO(SparseArray.__setitem__): remove special cases in
# ExtensionBlock.where
msg = "SparseArray does not support item assignment via setitem"
raise TypeError(msg)
def sort(
self,
*,
ascending: bool = True,
kind: SortKind = "quicksort",
na_position: str = "last",
) -> None:
raise NotImplementedError("SparseArray does not support in-place sort")
@classmethod
def _from_sequence(
cls, scalars, *, dtype: Dtype | None = None, copy: bool = False
) -> Self:
return cls(scalars, dtype=dtype)
@classmethod
def _from_factorized(cls, values, original) -> Self:
return cls(values, dtype=original.dtype)
def _cast_pointwise_result(self, values):
if not (isinstance(values, np.ndarray) and values.dtype == object):
values = construct_1d_object_array_from_listlike(values)
result = lib.maybe_convert_objects(values, convert_non_numeric=True)
if result.dtype.kind == self.dtype.kind:
try:
# e.g. test_groupby_agg_extensionView on GitHub (pinned to 3b7651241d)