{"record":{"id":"c762a3e7dc84f9f9","repo":"pandas-dev/pandas","slug":"values-shape-and-mask-shape-must-match","errorCode":null,"errorMessage":"values.shape and mask.shape must match","messagePattern":"values\\.shape and mask\\.shape must match","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/boolean.py","lineNumber":262,"sourceCode":"        ):\n            raise TypeError(\"Need to pass bool-like values\")\n\n    if mask is None and mask_values is None:\n        mask = np.zeros(values.shape, dtype=bool)\n    elif mask is None:\n        mask = mask_values\n    elif isinstance(mask, np.ndarray) and mask.dtype == np.bool_:\n        if mask_values is not None:\n            mask = mask | mask_values\n        elif copy:\n            mask = mask.copy()\n    else:\n        mask = np.array(mask, dtype=bool)\n        if mask_values is not None:\n            mask = mask | mask_values\n\n    if values.shape != mask.shape:\n        raise ValueError(\"values.shape and mask.shape must match\")\n\n    return values, mask\n\n\n@set_module(\"pandas.arrays\")\nclass BooleanArray(BaseMaskedArray):\n    \"\"\"\n    Array of boolean (True/False) data with missing values.\n\n    This is a pandas Extension array for boolean data, under the hood\n    represented by 2 numpy arrays: a boolean array with the data and\n    a boolean array with the mask (True indicating missing).\n\n    BooleanArray implements Kleene logic (sometimes called three-value\n    logic) for logical operations. See :ref:`boolean.kleene` for more.\n\n    To construct a BooleanArray from generic array-like input, use\n    :func:`pandas.array` specifying ``dtype=\"boolean\"`` (see examples","sourceCodeStart":244,"sourceCodeEnd":280,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/boolean.py#L244-L280","documentation":"coerce_to_array (boolean.py:262) verifies that the computed values array and the mask array have identical shapes; if they differ it raises ValueError. Mismatched lengths would silently misalign data and missingness, which pandas refuses.","triggerScenarios":"Calling coerce_to_array(values, mask=...) (or the BooleanArray constructor path) with a mask whose length differs from the values; internal callers that build a mask from a different-length index.","commonSituations":"Low-level library code that constructs a mask from a filtered/aggregate index; off-by-one bugs when deriving a mask from isna() on a subset; refactoring that decoupled values and mask construction.","solutions":["Ensure mask is derived from the same values: mask = isna(values) so lengths always match.","Validate len(values) == len(mask) before passing to coerce_to_array.","Build via the high-level pd.array(values, dtype='boolean') to let pandas compute the mask.","Realign/trim the mask to the values length explicitly and intentionally."],"exampleFix":"# before\ncoerce_to_array([True, False, True], mask=[False, False])  # raises\n\n# after\nmask = np.zeros(3, dtype=bool)\ncoerce_to_array([True, False, True], mask=mask)","handlingStrategy":"validation","validationCode":"def safe_coerce_with_mask(values, mask):\n    import numpy as np\n    values = np.asarray(values)\n    mask = np.asarray(mask)\n    if values.shape != mask.shape:\n        raise ValueError(f\"shape mismatch: {values.shape} vs {mask.shape}\")\n    return values, mask","typeGuard":"def shapes_match(values, mask) -> bool:\n    import numpy as np\n    return np.asarray(values).shape == np.asarray(mask).shape","tryCatchPattern":"try:\n    v, m = coerce_to_array(values, mask=mask)\nexcept ValueError as e:\n    if \"shape\" in str(e) and \"mask\" in str(e):\n        import numpy as np\n        mask = np.zeros(len(values), dtype=bool)\n        v, m = coerce_to_array(values, mask=mask)\n    else:\n        raise","preventionTips":["Derive the mask from the same values (isna(values))","Validate len(values)==len(mask)","Use pd.array to let pandas compute the mask"],"tags":["boolean","mask","shape-mismatch","validation"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}