pandas-dev/pandas · error · TypeError

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

Error message

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

What it means

safe_sort() is an internal utility that sorts values (and optionally remaps codes). Unlike many pandas functions, it has a strict type requirement for the values argument: only numpy.ndarray, ExtensionArray, and Index are accepted. Python lists, tuples, and pandas Series are explicitly rejected. This is because safe_sort operates at a low level where it needs direct access to the underlying array buffer.

Solutions

  1. Convert the values to np.asarray() before passing: safe_sort(np.asarray(my_list)).
  2. Use pd.Index() wrapping: safe_sort(pd.Index(my_list)).
  3. If you have a Series, pass series._values or series.index as appropriate.

Example fix

# before
from pandas.core.algorithms import safe_sort
safe_sort([3, 1, 2], codes=[0, 1, 2])

# after
safe_sort(np.array([3, 1, 2]), codes=np.array([0, 1, 2]))
Defensive patterns

Strategy: validation

Validate before calling

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

Type guard

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

Try / catch

try:
    result = safe_sort(values, codes)
except TypeError as e:
    if "safe_sort as values" in str(e):
        result = safe_sort(np.asarray(values), codes)
    else:
        raise

Prevention

When it happens

Trigger: Calling pandas.core.algorithms.safe_sort directly with a Python list as the values argument. Passing a pandas Series (which is not in the accepted type tuple) to safe_sort. Using a tuple or other sequence type that has not been converted to an ndarray or Index.

Common situations: Internal or library code that calls safe_sort directly. Wrapping pandas internals in a custom utility and passing unconverted list data. Misunderstanding the type requirements of internal vs. public pandas APIs.

Related errors


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

Appendix: 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 3b7651241d)