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

  1. Sort out-of-place: use arr.argsort() with take, or np.sort(arr) to obtain a sorted copy.
  2. Copy first to get a writable buffer: arr = arr.copy(); arr.sort().
  3. 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

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


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