{"record":{"id":"4f37d30f02f23424","repo":"pandas-dev/pandas","slug":"cannot-convert-float-nan-to-integer-4f37d3","errorCode":null,"errorMessage":"cannot convert float NaN to integer","messagePattern":"cannot convert float NaN to integer","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/period.py","lineNumber":1636,"sourceCode":"        ordinals = libperiod.period_ordinals_from_fields(\n            _field_to_int64(arrays[0]),\n            _field_to_int64(arrays[1]),\n            _field_to_int64(arrays[2]),\n            _field_to_int64(arrays[3]),\n            _field_to_int64(arrays[4]),\n            _field_to_int64(arrays[5]),\n            base,\n        )\n\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)","sourceCodeStart":1618,"sourceCodeEnd":1654,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/period.py#L1618-L1654","documentation":"Raised by _field_to_int64 when the input array has float dtype and contains NaN. Casting NaN to int64 silently yields a garbage ordinal, so pandas refuses, matching the scalar Period constructor's behavior.","triggerScenarios":"Passing a year/month/quarter/hour/... field built from a float column with missing values to PeriodIndex field-based construction; year = pd.Series([2020.0, np.nan]) used as the year field.","commonSituations":"Joining onto a dimension table that left nulls; user-uploaded spreadsheets with blank cells; downstream of merge that introduced NaNs.","solutions":["Drop or impute missing field values before constructing the PeriodIndex.","Use fillna on the offending column with a sensible default or dropna() the rows.","If missingness is meaningful, build a PeriodIndex for the valid subset and reindex."],"exampleFix":"# before\nyear = df['year'].astype(float)  # contains NaN\npd.PeriodIndex(year=year, quarter=df['q'], freq='Q')\n# after\nmask = df['year'].notna()\npd.PeriodIndex(year=df.loc[mask,'year'].astype(int), quarter=df.loc[mask,'q'], freq='Q')","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef fields_are_castable_to_int(values) -> bool:\n    arr = np.asarray(values)\n    if arr.dtype.kind == 'f':\n        return not np.isnan(arr).any()\n    return True","typeGuard":"def has_no_nan_float(values) -> bool:\n    arr = np.asarray(values)\n    return arr.dtype.kind != 'f' or not bool(np.isnan(arr).any())","tryCatchPattern":"try:\n    pi = pd.PeriodIndex(year=y, quarter=q, freq='Q')\nexcept ValueError as e:\n    if 'cannot convert float NaN' in str(e):\n        mask = np.asarray(y, dtype=float) == np.asarray(y, dtype=float)\n        pi = pd.PeriodIndex(year=np.asarray(y)[mask], quarter=np.asarray(q)[mask], freq='Q')\n    else:\n        raise","preventionTips":["Dropna field columns before constructing PeriodIndex.","Use integer dtype for year/quarter/month to surface NaN earlier as a different error.","Validate kind=='f' columns with np.isnan(...).any() before passing."],"tags":["pandas","period","nan","casting"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}