pandas-dev/pandas · error · ValueError

Mismatched Period array lengths

Error message

Mismatched Period array lengths

What it means

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.

Solutions

  1. Verify len() of each field array before construction: {k: len(v) for k,v in fields.items() if hasattr(v,'__len__')}.
  2. Broadcast scalars explicitly so only one length is in play.
  3. Realign with the same DataFrame index so all columns share length.

Example fix

# before
pd.PeriodIndex(year=df['year'], month=df['month_bad'], freq='M')  # lengths differ
# after
assert len(df['year']) == len(df['month'])
pd.PeriodIndex(year=df['year'], month=df['month'], freq='M')
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np

def field_lengths_match(*fields) -> bool:
    lengths = {len(np.asarray(f)) for f in fields if hasattr(f, '__len__') and not isinstance(f, str)}
    return len(lengths) <= 1

Type guard

def uniform_field_length(*fields) -> bool:
    lens = [len(f) for f in fields if hasattr(f, '__len__') and not isinstance(f, str)]
    return len(set(lens)) <= 1

Try / catch

try:
    pi = pd.PeriodIndex(year=y, month=m, freq='M')
except ValueError as e:
    if 'Mismatched Period array lengths' in str(e):
        n = min(len(y), len(m))
        pi = pd.PeriodIndex(year=y[:n], month=m[:n], freq='M')
    else:
        raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


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

Appendix: source

Thrown at pandas/core/arrays/period.py:1645

    return ordinals, freq


def _field_to_int64(values) -> np.ndarray:
    values = np.asarray(values)
    if values.dtype.kind == "f" and np.isnan(values).any():
        # Match the error raised by the scalar Period constructor; casting
        #  NaN to int64 would otherwise silently produce garbage ordinals.
        raise ValueError("cannot convert float NaN to integer")
    return values.astype(np.int64, copy=False)


def _make_field_arrays(*fields) -> list[np.ndarray]:
    length = None
    for x in fields:
        if isinstance(x, (list, tuple, np.ndarray, ABCSeries)):
            if length is not None and len(x) != length:
                raise ValueError("Mismatched Period array lengths")
            if length is None:
                length = len(x)

    # error: Argument 2 to "repeat" has incompatible type "Optional[int]"; expected
    # "Union[Union[int, integer[Any]], Union[bool, bool_], ndarray, Sequence[Union[int,
    # integer[Any]]], Sequence[Union[bool, bool_]], Sequence[Sequence[Any]]]"
    return [
        (
            np.asarray(x)
            if isinstance(x, (np.ndarray, list, tuple, ABCSeries))
            else np.repeat(x, length)  # type: ignore[arg-type]
        )
        for x in fields
    ]

View on GitHub (pinned to 3b7651241d)