pandas-dev/pandas · error · TypeError

Cannot create a {cls_name} from a MultiIndex.

Error message

Cannot create a {cls_name} from a MultiIndex.

What it means

Raised by ensure_arraylike_for_datetimelike when the supplied data is a pandas MultiIndex. A MultiIndex is a hierarchical (2-D-ish) structure and has no single axis to interpret as datetimes/timedeltas, so the datetimelike constructor refuses it rather than silently picking one level.

Source

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


# -------------------------------------------------------------------
# Shared Constructor Helpers


def ensure_arraylike_for_datetimelike(
    data, copy: bool, cls_name: str
) -> tuple[ArrayLike, bool]:
    if not hasattr(data, "dtype"):
        # e.g. list, tuple
        if not isinstance(data, (list, tuple)) and np.ndim(data) == 0:
            # i.e. generator
            data = list(data)

        data = construct_1d_object_array_from_listlike(data)
        copy = False
    elif isinstance(data, ABCMultiIndex):
        raise TypeError(f"Cannot create a {cls_name} from a MultiIndex.")
    else:
        data = extract_array(data, extract_numpy=True)

    if isinstance(data, IntegerArray) or (
        isinstance(data, ArrowExtensionArray) and data.dtype.kind in "iu"
    ):
        data = data.to_numpy("int64", na_value=iNaT)
        copy = False
    elif isinstance(data, ArrowExtensionArray):
        data = data._maybe_convert_datelike_array()
        data = data.to_numpy()
        copy = False
    elif not isinstance(data, (np.ndarray, ExtensionArray)):
        # GH#24539 e.g. xarray, dask object
        data = np.asarray(data)

    elif isinstance(data, ABCCategorical):
        # GH#18664 preserve tz in going DTI->Categorical->DTI

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Select the specific level: pd.DatetimeIndex(multiindex.get_level_values(level_name)).
  2. Flatten the MultiIndex with .to_flat_index() if you genuinely need tuples-as-values, then parse with to_datetime(format=...).
  3. Reset the index and pick the datetime column explicitly.

Example fix

# before
pd.to_datetime(df.index)  # df.index is a MultiIndex

# after
pd.to_datetime(df.index.get_level_values('ts'))
Defensive patterns

Strategy: type-guard

Validate before calling

if isinstance(data, pd.MultiIndex):
    raise TypeError('select a level: data.get_level_values(name)')

Type guard

def is_multiindex(x) -> bool:
    return isinstance(x, pd.MultiIndex)

Try / catch

try:
    pd.to_datetime(data)
except TypeError as e:
    if 'Cannot create a' in str(e) and 'MultiIndex' in str(e):
        pd.to_datetime(data.get_level_values(0))
    else: raise

Prevention

When it happens

Trigger: pd.DatetimeIndex(multiindex), pd.to_datetime(multiindex), pd.TimedeltaIndex(multiindex), or passing a MultiIndex as the data argument to a Series/Index constructor expecting datetimelike values.

Common situations: Forgotten .get_level_values(n) after a groupby/set_index. Passing df.index (a MultiIndex) where a single level was intended. Refactoring that lost a level selection.

Related errors


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