{"record":{"id":"6178602d6a054e1e","repo":"pandas-dev/pandas","slug":"values-shape-must-match-mask-shape","errorCode":null,"errorMessage":"values.shape must match mask.shape","messagePattern":"values\\.shape must match mask\\.shape","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/masked.py","lineNumber":159,"sourceCode":"\n    @classmethod\n    def _simple_new(cls, values: np.ndarray, mask: npt.NDArray[np.bool_]) -> Self:\n        result = BaseMaskedArray.__new__(cls)\n        result._data = values\n        result._mask = mask\n        return result\n\n    def __init__(\n        self, values: np.ndarray, mask: npt.NDArray[np.bool_], copy: bool = False\n    ) -> None:\n        # values is supposed to already be validated in the subclass\n        if not (isinstance(mask, np.ndarray) and mask.dtype == np.bool_):\n            raise TypeError(\n                \"mask should be boolean numpy array. Use \"\n                \"the 'pd.array' function instead\"\n            )\n        if values.shape != mask.shape:\n            raise ValueError(\"values.shape must match mask.shape\")\n\n        if copy:\n            values = values.copy()\n            mask = mask.copy()\n\n        self._data = values\n        self._mask = mask\n\n    @classmethod\n    def _from_sequence(cls, scalars, *, dtype=None, copy: bool = False) -> Self:\n        values, mask = cls._coerce_to_array(scalars, dtype=dtype, copy=copy)\n        return cls(values, mask)\n\n    def _cast_pointwise_result(self, values) -> ArrayLike:\n        if isna(values).all():\n            return type(self)._from_sequence(values, dtype=self.dtype)\n        if not (isinstance(values, np.ndarray) and values.dtype == object):\n            values = construct_1d_object_array_from_listlike(values)","sourceCodeStart":141,"sourceCodeEnd":177,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/masked.py#L141-L177","documentation":"Raised by BaseMaskedArray.__init__ when len(values) != len(mask). The data buffer and the mask must align element-for-element; a length mismatch indicates a programming error in how the masked array is being assembled.","triggerScenarios":"Constructing a masked array subclass directly with values of length N and mask of length M != N (e.g. data = np.arange(5), mask = np.zeros(3, bool)).","commonSituations":"Off-by-one slicing of the mask, reuse of a mask from a different column, or building arrays element-wise without recomputing the mask.","solutions":["Slice or pad the mask to match: mask = mask[:len(values)] or rebuild via pd.array(...).","Always derive the mask from the same source as values, e.g. mask = isna(values).","Prefer pd.array(values, dtype=...) which handles mask construction internally."],"exampleFix":"# before\nIntegerArray(np.arange(5), np.zeros(3, dtype=bool))\n\n# after\nmask = np.zeros(len(data), dtype=bool)\nIntegerArray(data, mask)","handlingStrategy":"validation","validationCode":"def matched_mask(values, mask):\n    mask = np.asarray(mask, dtype=bool)\n    if mask.shape != values.shape:\n        raise ValueError(f'mask shape {mask.shape} != values shape {values.shape}')\n    return mask","typeGuard":"def shapes_match(values, mask) -> bool:\n    return np.shape(values) == np.shape(mask)","tryCatchPattern":null,"preventionTips":["Derive masks from the same source as values: mask = isna(values).","Assert shapes match before constructing masked arrays.","Prefer pd.array(...) for public construction."],"tags":["masked-array","shape-mismatch","constructor"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}