pandas-dev/pandas · error · TypeError

Only np.ndarray, ExtensionArray, and Index objects are allow

Error message

Only np.ndarray, ExtensionArray, and Index objects are allowed to be passed to safe_sort as values

What it means

Raised by pandas.core.algorithms.safe_sort when the values argument is not an np.ndarray, ExtensionArray, or Index. safe_sort needs typed array semantics to sort and remap codes; a plain Python list/tuple/set is not accepted.

Source

Thrown at pandas/core/algorithms.py:1669

    Returns
    -------
    ordered : AnyArrayLike
        Sorted ``values``
    new_codes : ndarray
        Reordered ``codes``; returned when ``codes`` is not None.

    Raises
    ------
    TypeError
        * If ``values`` is not list-like or if ``codes`` is neither None
        nor list-like
        * If ``values`` cannot be sorted
    ValueError
        * If ``codes`` is not None and ``values`` contain duplicates.
    """
    if not isinstance(values, (np.ndarray, ABCExtensionArray, ABCIndex)):
        raise TypeError(
            "Only np.ndarray, ExtensionArray, and Index objects are allowed to "
            "be passed to safe_sort as values"
        )

    sorter = None
    ordered: AnyArrayLike

    # For integer values spanning a modest range, the codes remapping below
    #  can rank each value within that range (a counting sort) instead of
    #  argsorting.
    use_counting = False
    vmin = rng_size = 0
    if (
        codes is not None
        and isinstance(values, np.ndarray)
        and values.dtype.kind in "iu"
        and len(values) >= _MIN_COUNTING_SORT_LEN
    ):

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Convert values to np.ndarray or a pandas Index/Series first.
  2. Use np.sort for plain lists when you do not need code remapping.
  3. Validate the type at your boundary.

Example fix

# before
pd.core.algorithms.safe_sort([3, 1, 2])
# after
pd.core.algorithms.safe_sort(np.array([3, 1, 2]))
Defensive patterns

Strategy: type-guard

Validate before calling

import numpy as np, pandas as pd

def safe_sort_values(values, codes=None, **kw):
    if not isinstance(values, (np.ndarray, pd.Index, pd.api.extensions.ExtensionArray)):
        values = np.asarray(values)
    return pd.core.algorithms.safe_sort(values, codes, **kw)

Type guard

import numpy as np, pandas as pd

def is_safe_sort_values(v) -> bool:
    return isinstance(v, (np.ndarray, pd.Index, pd.api.extensions.ExtensionArray))

Prevention

When it happens

Trigger: Calling pd.core.algorithms.safe_sort([3, 1, 2]) with a list; passing a set or scalar as values; internal callers (e.g. unique/factorize) that forgot to coerce to an array.

Common situations: Using safe_sort directly with native Python containers; refactors that removed an np.asarray step upstream.

Related errors


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