pandas-dev/pandas · error · NotImplementedError

The 'sort' keyword in

Error message

The 'sort' keyword in {type(self).__name__}.factorize is not supported. To factorize with sort, call pd.factorize(obj, sort=True) instead.

What it means

Raised by DatetimeLikeArrayMixin.factorize when sort=True is passed directly to the ExtensionArray.factorize method. Sorting the uniques of a datetime-like array requires reordering and is intentionally implemented only at the top-level pd.factorize(obj, sort=True); the array-level method refuses to silently do extra work or diverge in semantics.

Solutions

  1. Use pd.factorize(obj, sort=True) at the module level.
  2. If you must use the method, call obj.factorize() then sort the resulting codes/uniques yourself.
  3. Lint/guard callsites so sort=True is never passed to the array method.

Example fix

// before
codes, uniques = idx.factorize(sort=True)  # NotImplementedError

// after
codes, uniques = pd.factorize(idx, sort=True)
Defensive patterns

Strategy: validation

Validate before calling

def factorize_safe(obj, sort=False):
    if sort:
        return pd.factorize(obj, sort=True)
    return obj.factorize() if hasattr(obj, "factorize") else pd.factorize(obj)

Type guard

def is_array_factorize_no_sort(method_name, kwargs) -> bool:
    return method_name == "factorize" and kwargs.get("sort", False) is True

Try / catch

try:
    codes, uniques = obj.factorize(sort=True)
except NotImplementedError as e:
    if "sort" in str(e) and "pd.factorize" in str(e):
        codes, uniques = pd.factorize(obj, sort=True)
    else:
        raise

Prevention

When it happens

Trigger: Calling obj.factorize(sort=True) on a DatetimeArray/TimedeltaArray/PeriodArray (or via the .values accessor), instead of the module-level pd.factorize.

Common situations: Refactoring code that called pd.factorize into the method form for chaining; assuming the method mirrors numpy/sklearn factorize signatures fully; typing stubs that list sort as a valid kwarg.

Related errors


AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11). Data as JSON: /api/errors/a164ea4e49e48524. Report an issue: GitHub.

Appendix: source

Thrown at pandas/core/arrays/datetimelike.py:2380

        return nanops.nanall(self._ndarray, axis=axis, skipna=skipna, mask=self.isna())

    # --------------------------------------------------------------
    # ExtensionArray Interface

    def _values_for_json(self) -> np.ndarray:
        # Small performance bump vs the base class which calls np.asarray(self)
        if isinstance(self.dtype, np.dtype):
            return self._ndarray
        return super()._values_for_json()

    def factorize(
        self,
        use_na_sentinel: bool = True,
        sort: bool = False,
    ):
        if sort:
            raise NotImplementedError(
                f"The 'sort' keyword in {type(self).__name__}.factorize is not "
                "supported. To factorize with sort, call pd.factorize(obj, sort=True) "
                "instead."
            )
        return super().factorize(use_na_sentinel=use_na_sentinel)

    def interpolate(
        self,
        *,
        method: InterpolateOptions,
        axis: int,
        index: Index,
        limit,
        limit_direction,
        limit_area,
        copy: bool,
        **kwargs,
    ) -> Self:

View on GitHub (pinned to 3b7651241d)