pandas-dev/pandas · error · ValueError
Cannot modify read-only array
Error message
Cannot modify read-only array
What it means
NDArrayBackedExtensionArray.sort sorts in place by writing reordered values back into the backing ndarray via self._ndarray[:] = .... If the backing buffer is read-only (the _readonly flag is set, propagated from views of read-only sources), the in-place write cannot succeed and pandas raises ValueError before attempting it.
Source
Thrown at pandas/core/arrays/_mixins.py:243
# override base class by adding axis keyword
validate_bool_kwarg(skipna, "skipna")
if not skipna and self._hasna:
raise ValueError("Encountered an NA value with skipna=False")
return nargminmax(self, "argmax", axis=axis)
def unique(self) -> Self:
new_data = unique(self._ndarray)
return self._from_backing_data(new_data)
def sort(
self,
*,
ascending: bool = True,
kind: SortKind = "quicksort",
na_position: str = "last",
) -> None:
if self._readonly:
raise ValueError("Cannot modify read-only array")
sort_indices = self.argsort(
ascending=ascending, kind=kind, na_position=na_position
)
self._ndarray[:] = self._ndarray[sort_indices]
@classmethod
def _concat_same_type(
cls,
to_concat: Sequence[Self],
axis: AxisInt = 0,
) -> Self:
"""
Concatenate multiple arrays of this dtype.
Parameters
----------
to_concat : sequence of this type
View on GitHub (pinned to 71959b8cb9)
Solutions
- Sort out-of-place: use arr.argsort() with take, or np.sort(arr) to obtain a sorted copy.
- Copy first to get a writable buffer: arr = arr.copy(); arr.sort().
- Avoid relying on in-place sort on slices/views of read-only data.
Example fix
// before arr.sort() // after arr = arr.copy() arr.sort()
Defensive patterns
Strategy: validation
Validate before calling
def safe_sort(arr):
if getattr(arr, "_readonly", False):
arr = arr.copy()
arr.sort()
return arr Prevention
- Copy read-only arrays before in-place ops
- Prefer argsort()+take or np.sort() over in-place sort on views
When it happens
Trigger: Calling arr.sort() on a read-only extension array obtained from a numpy array with WRITEABLE=False, a memory-mapped buffer, np.frombuffer, or a view propagated from a read-only parent.
Common situations: Data loaded read-only from disk/mmap, or arrays derived from .values round-trips; expecting sort to return a copy.
Related errors
- {left_base!r} is not {right_base!r}
- {left_base!r} is {right_base!r}
- Cannot modify read-only array
- {type(self)} does not implement __setitem__.
- Cannot modify read-only array
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/63f6255712af0015.
Report an issue: GitHub.