{"record":{"id":"a2681b971b3f883b","repo":"pandas-dev/pandas","slug":"mismatched-period-array-lengths","errorCode":null,"errorMessage":"Mismatched Period array lengths","messagePattern":"Mismatched Period array lengths","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/period.py","lineNumber":1645,"sourceCode":"\n    return ordinals, freq\n\n\ndef _field_to_int64(values) -> np.ndarray:\n    values = np.asarray(values)\n    if values.dtype.kind == \"f\" and np.isnan(values).any():\n        # Match the error raised by the scalar Period constructor; casting\n        #  NaN to int64 would otherwise silently produce garbage ordinals.\n        raise ValueError(\"cannot convert float NaN to integer\")\n    return values.astype(np.int64, copy=False)\n\n\ndef _make_field_arrays(*fields) -> list[np.ndarray]:\n    length = None\n    for x in fields:\n        if isinstance(x, (list, tuple, np.ndarray, ABCSeries)):\n            if length is not None and len(x) != length:\n                raise ValueError(\"Mismatched Period array lengths\")\n            if length is None:\n                length = len(x)\n\n    # error: Argument 2 to \"repeat\" has incompatible type \"Optional[int]\"; expected\n    # \"Union[Union[int, integer[Any]], Union[bool, bool_], ndarray, Sequence[Union[int,\n    # integer[Any]]], Sequence[Union[bool, bool_]], Sequence[Sequence[Any]]]\"\n    return [\n        (\n            np.asarray(x)\n            if isinstance(x, (np.ndarray, list, tuple, ABCSeries))\n            else np.repeat(x, length)  # type: ignore[arg-type]\n        )\n        for x in fields\n    ]\n","sourceCodeStart":1627,"sourceCodeEnd":1660,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/period.py#L1627-L1660","documentation":"Raised by _make_field_arrays when two or more field arrays (year, month, day, hour, minute, second, quarter) have differing lengths. Field-based period construction broadcasts scalars but requires every array field to share one length.","triggerScenarios":"pd.PeriodIndex(year=[2020,2021], month=[1,2,3], freq='M'); mixing a length-3 quarter array with a length-2 year array; one field pulled from a misaligned column.","commonSituations":"Mismatched DataFrame columns after a filter/merge; broadcasting expectation mismatch (one field expected to scalar-broadcast but is an array); pipeline typo pulling wrong column.","solutions":["Verify len() of each field array before construction: {k: len(v) for k,v in fields.items() if hasattr(v,'__len__')}.","Broadcast scalars explicitly so only one length is in play.","Realign with the same DataFrame index so all columns share length."],"exampleFix":"# before\npd.PeriodIndex(year=df['year'], month=df['month_bad'], freq='M')  # lengths differ\n# after\nassert len(df['year']) == len(df['month'])\npd.PeriodIndex(year=df['year'], month=df['month'], freq='M')","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef field_lengths_match(*fields) -> bool:\n    lengths = {len(np.asarray(f)) for f in fields if hasattr(f, '__len__') and not isinstance(f, str)}\n    return len(lengths) <= 1","typeGuard":"def uniform_field_length(*fields) -> bool:\n    lens = [len(f) for f in fields if hasattr(f, '__len__') and not isinstance(f, str)]\n    return len(set(lens)) <= 1","tryCatchPattern":"try:\n    pi = pd.PeriodIndex(year=y, month=m, freq='M')\nexcept ValueError as e:\n    if 'Mismatched Period array lengths' in str(e):\n        n = min(len(y), len(m))\n        pi = pd.PeriodIndex(year=y[:n], month=m[:n], freq='M')\n    else:\n        raise","preventionTips":["Pull all field columns from the same aligned DataFrame.","Broadcast scalars explicitly to avoid accidental length mismatch.","Add a shape pre-check in your helper that builds PeriodIndex from fields."],"tags":["pandas","period","shape","validation"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}