pandas-dev/pandas · error · NotImplementedError

> 1 ndim Categorical are not supported at this time

Error message

> 1 ndim Categorical are not supported at this time

What it means

Raised in the Categorical constructor when the input values array has more than one dimension (ndim > 1). Categorical only models 1-D enumeration data; multi-dimensional arrays are preemptively rejected before sanitize_array would raise a vaguer error.

Source

Thrown at pandas/core/arrays/categorical.py:435

        # sanitize input
        vdtype = getattr(values, "dtype", None)
        if isinstance(vdtype, CategoricalDtype):
            if dtype.categories is None:
                dtype = CategoricalDtype(values.categories, dtype.ordered)
        elif isinstance(values, range):
            from pandas.core.indexes.range import RangeIndex

            values = RangeIndex(values)
        elif not isinstance(values, (ABCIndex, ABCSeries, ExtensionArray)):
            values = com.convert_to_list_like(values)
            if isinstance(values, list) and len(values) == 0:
                # By convention, empty lists result in object dtype:
                values = np.array([], dtype=object)
            elif isinstance(values, np.ndarray):
                if values.ndim > 1:
                    # preempt sanitize_array from raising ValueError
                    raise NotImplementedError(
                        "> 1 ndim Categorical are not supported at this time"
                    )
                values = sanitize_array(values, None)
            else:
                # i.e. must be a list
                arr = sanitize_array(values, None)
                null_mask = isna(arr)
                if null_mask.any():
                    # We remove null values here, then below will re-insert
                    #  them, grep "full_codes"
                    arr_list = [values[idx] for idx in np.where(~null_mask)[0]]

                    # GH#44900 Do not cast to float if we have only missing values
                    if arr_list or arr.dtype == "object":
                        sanitize_dtype = None
                    else:
                        sanitize_dtype = arr.dtype

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Flatten or select a single column: `pd.Categorical(arr.ravel())` or `pd.Categorical(df['col'])`.
  2. If you need per-column categoricals, apply Categorical to each column of the 2-D structure separately.
  3. Validate `np.asarray(values).ndim == 1` before constructing.

Example fix

# before
pd.Categorical(np.zeros((3, 3)))
# after
pd.Categorical(np.zeros((3, 3)).ravel())
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np

def to_categorical_1d(values, **kw):
    arr = np.asarray(values)
    if arr.ndim > 1:
        raise ValueError(f"expected 1-D, got ndim={arr.ndim}")
    import pandas as pd
    return pd.Categorical(arr, **kw)

Type guard

def is_1d_arraylike(x) -> bool:
    import numpy as np
    return hasattr(x, 'ndim') and np.asarray(x).ndim == 1

Try / catch

try:
    cat = pd.Categorical(values)
except NotImplementedError as e:
    if 'ndim' in str(e):
        import numpy as np
        cat = pd.Categorical(np.asarray(values).ravel())
    else:
        raise

Prevention

When it happens

Trigger: Passing a 2-D numpy array or a nested list-of-lists to `pd.Categorical(...)`, e.g. `pd.Categorical(np.zeros((3, 3)))` or `pd.Categorical([[1,2],[3,4]])`.

Common situations: Accidentally passing an entire DataFrame's values or a matrix instead of a single column; reshaping data and forgetting to flatten.

Related errors


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