{"record":{"id":"b129afab8f3ed96d","repo":"pandas-dev/pandas","slug":"cannot-create-a-cls-name-from-a-multiindex","errorCode":null,"errorMessage":"Cannot create a {cls_name} from a MultiIndex.","messagePattern":"Cannot create a (.+?) from a MultiIndex\\.","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/datetimelike.py","lineNumber":2466,"sourceCode":"\n\n# -------------------------------------------------------------------\n# Shared Constructor Helpers\n\n\ndef ensure_arraylike_for_datetimelike(\n    data, copy: bool, cls_name: str\n) -> tuple[ArrayLike, bool]:\n    if not hasattr(data, \"dtype\"):\n        # e.g. list, tuple\n        if not isinstance(data, (list, tuple)) and np.ndim(data) == 0:\n            # i.e. generator\n            data = list(data)\n\n        data = construct_1d_object_array_from_listlike(data)\n        copy = False\n    elif isinstance(data, ABCMultiIndex):\n        raise TypeError(f\"Cannot create a {cls_name} from a MultiIndex.\")\n    else:\n        data = extract_array(data, extract_numpy=True)\n\n    if isinstance(data, IntegerArray) or (\n        isinstance(data, ArrowExtensionArray) and data.dtype.kind in \"iu\"\n    ):\n        data = data.to_numpy(\"int64\", na_value=iNaT)\n        copy = False\n    elif isinstance(data, ArrowExtensionArray):\n        data = data._maybe_convert_datelike_array()\n        data = data.to_numpy()\n        copy = False\n    elif not isinstance(data, (np.ndarray, ExtensionArray)):\n        # GH#24539 e.g. xarray, dask object\n        data = np.asarray(data)\n\n    elif isinstance(data, ABCCategorical):\n        # GH#18664 preserve tz in going DTI->Categorical->DTI","sourceCodeStart":2448,"sourceCodeEnd":2484,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/datetimelike.py#L2448-L2484","documentation":"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.","triggerScenarios":"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)).","commonSituations":"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.","solutions":["Select the relevant level first: pd.DatetimeIndex(multi.get_level_values('ts')).","Reset the index: df.reset_index()['ts'] to obtain a flat Series.","Flatten explicitly with np.asarray or to_numpy() only after deciding the target shape."],"exampleFix":"// before\nmi = pd.MultiIndex.from_arrays([['a','b'], pd.to_datetime(['2020-01-01','2020-02-01'])])\npd.DatetimeIndex(mi)  # TypeError: Cannot create a DatetimeIndex from a MultiIndex.\n\n// after\npd.DatetimeIndex(mi.get_level_values(1))","handlingStrategy":"type-guard","validationCode":"def to_dt_index(data):\n    if isinstance(data, pd.MultiIndex):\n        raise TypeError(\"Select a level first: data.get_level_values(n)\")\n    return pd.DatetimeIndex(data)","typeGuard":"def is_multiindex(data) -> bool:\n    return isinstance(data, pd.MultiIndex)","tryCatchPattern":"try:\n    idx = pd.DatetimeIndex(data)\nexcept TypeError as e:\n    if \"from a MultiIndex\" in str(e) and isinstance(data, pd.MultiIndex):\n        idx = pd.DatetimeIndex(data.get_level_values(-1))\n    else:\n        raise","preventionTips":["Always select a level explicitly when converting from a MultiIndex.","Add a type check at API boundaries that accept Index inputs.","Reset_index() before feeding an index into a 1-D constructor."],"tags":["pandas","multiindex","constructor","datetimeindex","api-misuse"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}