pandas-dev/pandas · error · TypeError

Cannot create a from a MultiIndex.

Error message

Cannot create a {cls_name} from a MultiIndex.

What it means

Raised by ensure_arraylike_for_datetimelike when the input data is an ABCMultiIndex. Constructing a DatetimeIndex/TimedeltaIndex/PeriodArray from a MultiIndex is ambiguous (which level? flatten?), so the constructor helper rejects it explicitly rather than silently flattening or picking a level.

Solutions

  1. Select the relevant level first: pd.DatetimeIndex(multi.get_level_values('ts')).
  2. Reset the index: df.reset_index()['ts'] to obtain a flat Series.
  3. Flatten explicitly with np.asarray or to_numpy() only after deciding the target shape.

Example fix

// before
mi = pd.MultiIndex.from_arrays([['a','b'], pd.to_datetime(['2020-01-01','2020-02-01'])])
pd.DatetimeIndex(mi)  # TypeError: Cannot create a DatetimeIndex from a MultiIndex.

// after
pd.DatetimeIndex(mi.get_level_values(1))
Defensive patterns

Strategy: type-guard

Validate before calling

def to_dt_index(data):
    if isinstance(data, pd.MultiIndex):
        raise TypeError("Select a level first: data.get_level_values(n)")
    return pd.DatetimeIndex(data)

Type guard

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

Try / catch

try:
    idx = pd.DatetimeIndex(data)
except TypeError as e:
    if "from a MultiIndex" in str(e) and isinstance(data, pd.MultiIndex):
        idx = pd.DatetimeIndex(data.get_level_values(-1))
    else:
        raise

Prevention

When it happens

Trigger: pd.DatetimeIndex(multi_index), pd.TimedeltaIndex(multi_index), or passing a MultiIndex where a 1-D datetime-like array is expected (e.g. Series constructor with a datetime dtype, or pd.period_array(multi_index)).

Common situations: Resetting/flattening a MultiIndex incorrectly; feeding df.index (a MultiIndex) into a datetime constructor without selecting a level; type-coercion helpers that assume any Index is acceptable.

Related errors


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

Appendix: source

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


# -------------------------------------------------------------------
# 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 3b7651241d)