Skip to content

Treat masked values as missing in in-place binary operations - #11955

Open
AsadullahMaliyawala wants to merge 3 commits into
pydata:mainfrom
AsadullahMaliyawala:fix-inplace-masked-array
Open

AsadullahMaliyawala wants to merge 3 commits into
pydata:mainfrom
AsadullahMaliyawala:fix-inplace-masked-array

Conversation

@AsadullahMaliyawala

Copy link
Copy Markdown

Description

#11911 made binary operations with a NumPy masked array treat masked values as missing, but the in-place path (Variable._inplace_binary_op, also used by DataArray) still passes the raw masked array to the operator. Since ndarray += MaskedArray writes into the plain ndarray, the mask is silently dropped and the data underneath it is used:

import numpy as np
import xarray as xr

masked = np.ma.array([1.0, 2.0, 3.0], mask=[False, True, False])

da = xr.DataArray([1.0, 2.0, 3.0], dims="x")
(da + masked).values  # [ 2., nan,  6.]

ds = xr.Dataset({"a": ("x", [1.0, 2.0, 3.0])})
ds += masked
ds.a.values           # [ 2., nan,  6.]

da += masked
da.values             # main: [2., 4., 6.]  (the masked 2.0 is used)
                      # this PR: [ 2., nan,  6.]

This applies the same as_compatible_data conversion in _inplace_binary_op. When nothing is masked, the underlying data is used as is, so int_da += np.ma.array([1, 2, 3]) keeps working with an integer dtype (as_compatible_data always promotes masked integer arrays to float, which can't be cast back in place). An integer array combined in place with a masked array that actually has masked elements now raises numpy's casting error, the same as int_da += np.array([1.0, np.nan]), instead of silently using the masked values.

Found while reviewing #11911; it is not released yet, so I added the entry next to its whats-new entry.

Checklist

  • Tests added
  • User visible changes (including notable bug fixes) are documented in whats-new.rst

AI Disclosure

  • This PR contains AI-generated content.
    • I have tested any AI-generated content in my PR.
    • I take responsibility for any AI-generated content in my PR.
      Tools: Claude Code (Claude Opus 5.5), used to review the recent changes, write the patch and tests, and run the tests locally.

AsadullahMaliyawala and others added 3 commits November 30, 2026 20:57
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@headtr1ck headtr1ck added the plan to merge Final call for comments label Nov 30, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

plan to merge Final call for comments

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants