{"record":{"id":"c5e3852556ca83d9","repo":"pandas-dev/pandas","slug":"value-should-be-a-period-got-value-instead","errorCode":null,"errorMessage":"'value' should be a Period. Got '{value}' instead.","messagePattern":"'value' should be a Period\\. Got '(.+?)' instead\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/period.py","lineNumber":398,"sourceCode":"        return cls._simple_new(subarr, dtype=dtype)\n\n    # -----------------------------------------------------------------\n    # DatetimeLike Interface\n\n    def _unbox_scalar(\n        self,\n        # error: Argument 1 of \"_unbox_scalar\" is incompatible with supertype\n        # \"pandas.core.arrays.datetimelike.DatetimeLikeArrayMixin\"; supertype\n        #  defines the argument type as \"Period | Timestamp | Timedelta | NaTType\"\n        value: Period | NaTType,  # type: ignore[override]\n    ) -> np.int64:\n        if value is NaT:\n            return np.int64(value._value)\n        elif isinstance(value, self._scalar_type):\n            self._check_compatible_with(value)\n            return np.int64(value.ordinal)\n        else:\n            raise ValueError(f\"'value' should be a Period. Got '{value}' instead.\")\n\n    def _scalar_from_string(self, value: str) -> Period:\n        return Period(value, freq=self.freq)\n\n    def _check_compatible_with(\n        self,\n        #  error: Argument 1 of \"_check_compatible_with\" is incompatible with\n        # supertype \"pandas.core.arrays.datetimelike.DatetimeLikeArrayMixin\";\n        # supertype defines the argument type as \"Period | Timestamp | Timedelta\n        # | NaTType\"\n        other: Period | NaTType | PeriodArray,  # type: ignore[override]\n    ) -> None:\n        if other is NaT:\n            return\n        elif isinstance(other, Period):\n            self._require_matching_unit(other._dtype._freqstr)\n        else:\n            # error: Item \"NaTType\" of \"NaTType | PeriodArray\" has no","sourceCodeStart":380,"sourceCodeEnd":416,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/period.py#L380-L416","documentation":"Raised by PeriodArray._unbox_scalar when the supplied value is neither NaT nor an instance of self._scalar_type (i.e. pd.Period). _unbox_scalar converts a scalar to its int64 ordinal for internal ops; only Period (matching freq) and NaT are valid inputs. Anything else (int, str, Timestamp, datetime) is rejected with the offending value shown.","triggerScenarios":"Internal call from searchsorted/take/fillna with a non-Period scalar. PeriodIndex.get_loc('2023-01-01') where the string isn't converted to a Period first. Passing an int ordinal where a Period is expected.","commonSituations":"Mixing PeriodIndex with raw strings/Timestamps in lookups; assuming the index will coerce the scalar; downstream code that passes ordinals directly into Period-aware ops.","solutions":["Convert the scalar to a Period first: pd.Period(value, freq=idx.freq).","Use NaT for missing-value slots instead of None/NaN.","For lookups, rely on the public Index methods which perform conversion; avoid calling _unbox_scalar directly."],"exampleFix":"# before\nidx = pd.period_range('2023', periods=3, freq='M')\nidx._unbox_scalar('2023-01')  # raises\n\n# after\nidx._unbox_scalar(pd.Period('2023-01', freq='M'))","handlingStrategy":"type-guard","validationCode":"import pandas as pd\n\ndef unbox_for_period(period_array, value):\n    if value is pd.NaT:\n        return period_array._unbox_scalar(pd.NaT)\n    if not isinstance(value, pd.Period):\n        value = pd.Period(value, freq=period_array.freq)\n    return period_array._unbox_scalar(value)","typeGuard":"import pandas as pd\n\ndef is_period_or_nat(value) -> bool:\n    return value is pd.NaT or isinstance(value, pd.Period)","tryCatchPattern":"try:\n    idx._unbox_scalar(value)\nexcept ValueError as e:\n    if 'should be a Period' in str(e):\n        idx._unbox_scalar(pd.Period(value, freq=idx.freq))\n    else:\n        raise","preventionTips":["Convert lookups to pd.Period(value, freq=idx.freq) before passing to period index internals.","Use pd.NaT (not None/np.nan) for missing period scalars.","Avoid calling _unbox_scalar directly; prefer public Index lookup methods."],"tags":["pandas","period","scalar","internal","validation"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}