{"record":{"id":"f39a35db80433df7","repo":"pandas-dev/pandas","slug":"putmask-mask-and-data-must-be-the-same-size","errorCode":null,"errorMessage":"putmask: mask and data must be the same size","messagePattern":"putmask: mask and data must be the same size","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/array_algos/putmask.py","lineNumber":110,"sourceCode":"            np.place(values, mask, new)\n            # i.e. values[mask] = new\n        elif mask.shape[-1] == shape[-1] or shape[-1] == 1:\n            np.putmask(values, mask, new)\n        else:\n            raise ValueError(\"cannot assign mismatch length to masked array\")\n    else:\n        np.putmask(values, mask, new)\n\n\ndef validate_putmask(\n    values: ArrayLike | MultiIndex, mask: np.ndarray\n) -> tuple[npt.NDArray[np.bool_], bool]:\n    \"\"\"\n    Validate mask and check if this putmask operation is a no-op.\n    \"\"\"\n    mask = extract_bool_array(mask)\n    if mask.shape != values.shape:\n        raise ValueError(\"putmask: mask and data must be the same size\")\n\n    noop = not mask.any()\n    return mask, noop\n\n\ndef extract_bool_array(mask: ArrayLike) -> npt.NDArray[np.bool_]:\n    \"\"\"\n    If we have a SparseArray or BooleanArray, convert it to ndarray[bool].\n    \"\"\"\n    if isinstance(mask, ExtensionArray):\n        # We could have BooleanArray, Sparse[bool], ...\n        #  Except for BooleanArray, this is equivalent to just\n        #  np.asarray(mask, dtype=bool)\n        mask = mask.to_numpy(dtype=bool, na_value=False)\n\n    mask = np.asarray(mask, dtype=bool)\n    return mask\n","sourceCodeStart":92,"sourceCodeEnd":128,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/array_algos/putmask.py#L92-L128","documentation":"Raised by validate_putmask (putmask.py:110) as a ValueError when the boolean mask passed to a putmask/where operation has a different shape than the target values array. Before any assignment pandas validates mask.shape == values.shape so the boolean selection stays positional and unambiguous; a shape mismatch (including wrong number of dims) is rejected immediately.","triggerScenarios":"df.where(mask, ...) where mask is a 1-D array applied to a 2-D frame, or a 2-D mask applied to a 1-D Series; mask built from a different column or a differently-indexed Series that wasn't broadcast; mask from np.random with the wrong size. Hit at putmask.py:108-110 when mask.shape != values.shape.","commonSituations":"Applying a per-column mask to a whole frame without broadcasting; mismatched shapes after a transpose; mask computed on a subset and not realigned; passing a list of booleans whose length differs from the data.","solutions":["Ensure mask has the same shape as values: reshape/broadcast first, e.g. mask = mask.reshape(df.shape) or use a column-aligned boolean Series.","Construct the mask from the frame itself so shapes stay aligned: mask = df > 0.","If masking a single column, select it first: df['col'].where(mask, other)."],"exampleFix":"// before\ndf = pd.DataFrame({'a':[1,2],'b':[3,4]})\ndf.where([True, False], other=0)  # 1-D mask on 2-D frame\n// after\ndf.where(pd.DataFrame([[True,False],[True,False]], columns=df.columns), other=0)\n// or per-column\ndf['a'].where([True, False], other=0)","handlingStrategy":"validation","validationCode":"import numpy as np\nmask_arr = np.asarray(mask)\nif mask_arr.shape != np.asarray(values).shape:\n    raise ValueError(f'mask shape {mask_arr.shape} != values shape {np.asarray(values).shape}')","typeGuard":"def putmask_shape_matches(values, mask) -> bool:\n    import numpy as np\n    return np.asarray(mask).shape == np.asarray(values).shape","tryCatchPattern":"try:\n    df.where(mask, other=other)\nexcept ValueError as e:\n    if 'mask and data must be the same size' in str(e):\n        df.where(np.broadcast_to(mask, df.shape), other=other)\n    else:\n        raise","preventionTips":["Build masks from the frame itself (df > 0) so shapes stay aligned.","Broadcast 1-D masks explicitly before applying to a 2-D frame."],"tags":["pandas","where","mask","putmask","shape-mismatch"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}