{"record":{"id":"1dbd15a7486ee6f8","repo":"pandas-dev/pandas","slug":"invalid-dtype-dtype-for-periodarray","errorCode":null,"errorMessage":"Invalid dtype {dtype} for PeriodArray","messagePattern":"Invalid dtype (.+?) for PeriodArray","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/period.py","lineNumber":230,"sourceCode":"        \"days_in_month\",\n    ]\n    # GH#46768 - deprecated but still need to be accessible via .dt accessor\n    _deprecated_ops: list[str] = [\"dayofweek\", \"dayofyear\", \"daysinmonth\"]\n    _datetimelike_ops: list[str] = (\n        _field_ops + _object_ops + _bool_ops + _deprecated_ops\n    )\n    _datetimelike_methods: list[str] = [\"strftime\", \"to_timestamp\", \"asfreq\"]\n\n    _dtype: PeriodDtype\n\n    # --------------------------------------------------------------------\n    # Constructors\n\n    def __init__(self, values, dtype: Dtype | None = None, copy: bool = False) -> None:\n        if dtype is not None:\n            dtype = pandas_dtype(dtype)\n            if not isinstance(dtype, PeriodDtype):\n                raise ValueError(f\"Invalid dtype {dtype} for PeriodArray\")\n\n        if isinstance(values, ABCSeries):\n            values = values._values\n            if not isinstance(values, type(self)):\n                raise TypeError(\"Incorrect dtype\")\n\n        elif isinstance(values, ABCPeriodIndex):\n            values = values._values\n\n        if isinstance(values, type(self)):\n            if dtype is not None and dtype != values.dtype:\n                raise raise_on_incompatible(values, dtype.freq)\n            values, dtype = values._ndarray, values.dtype\n\n        if not copy:\n            values = np.asarray(values, dtype=\"int64\")\n        else:\n            values = np.array(values, dtype=\"int64\", copy=copy)","sourceCodeStart":212,"sourceCodeEnd":248,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/period.py#L212-L248","documentation":"Raised by PeriodArray.__init__ when a dtype argument is supplied, resolved via pandas_dtype, but is not a PeriodDtype. PeriodArray is meaningful only with a frequency; passing an incompatible dtype (e.g. int64, datetime64, a string like 'M' that isn't a period unit) is rejected. The resolved dtype is included in the message.","triggerScenarios":"PeriodArray([2023, 2024], dtype='int64'); PeriodArray(values, dtype='datetime64[ns]'); PeriodArray(values, dtype='M') where 'M' parses to a non-Period dtype. Direct constructor use with the wrong dtype kind.","commonSituations":"Confusing Period freq strings ('M' = month period) with numpy/dateutil units; passing a plain frequency string where a period dtype ('period[M]') is required; copy-pasting dtype from a DatetimeIndex.","solutions":["Pass a proper period dtype: dtype='period[M]' or dtype=PeriodDtype('M').","Omit dtype and let pandas infer the freq from Period scalars in the input.","Build via pd.period_range(start, end, freq='M') which handles dtype for you."],"exampleFix":"# before\npd.PeriodArray(pd.Series([pd.Period('2023', freq='Y')]), dtype='int64')  # raises\n\n# after\npd.PeriodArray(pd.Series([pd.Period('2023', freq='Y')]), dtype='period[Y')","handlingStrategy":"validation","validationCode":"import pandas as pd\n\ndef make_period_array(values, freq=None):\n    dtype = f'period[{freq}]' if freq else None\n    if dtype is not None:\n        pd.core.dtypes.common.pandas_dtype(dtype)  # raises early if invalid\n    return pd.PeriodArray(values, dtype=dtype)","typeGuard":"from pandas.core.dtypes.dtypes import PeriodDtype\n\ndef is_period_dtype_like(dtype) -> bool:\n    try:\n        return isinstance(pd.core.dtypes.common.pandas_dtype(dtype), PeriodDtype)\n    except TypeError:\n        return False","tryCatchPattern":"try:\n    pd.PeriodArray(values, dtype=dtype)\nexcept ValueError as e:\n    if 'Invalid dtype' in str(e):\n        pd.PeriodArray(values, dtype=f'period[{dtype}]')\n    else:\n        raise","preventionTips":["Always use the 'period[<freq>]' form for period dtypes (e.g. 'period[M]').","Use pd.period_range() / pd.PeriodIndex() which manage dtype for you.","Don't confuse period freq strings with numpy datetime64 units."],"tags":["pandas","period","constructor","dtype","freq"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}