Skip to content

Fix as_compatible_data for read-only np.ma.MaskedArray #7788

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ New Features
- Add support for lshift and rshift binary operators (``<<``, ``>>``) on
:py:class:`xr.DataArray` of type :py:class:`int` (:issue:`7727` , :pull:`7741`).
By `Alan Brammer <https://github.com/abrammer>`_.
- Fix `as_compatible_data` for masked float arrays, now always creates a copy when mask is present (:issue:`2377`, :pull:`7788`).
By `Max Hollmann <https://github.com/maxhollmann>`_.


Breaking changes
Expand Down
3 changes: 1 addition & 2 deletions xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,8 +274,7 @@ def as_compatible_data(data, fastpath=False):
mask = np.ma.getmaskarray(data)
if mask.any():
dtype, fill_value = dtypes.maybe_promote(data.dtype)
data = np.asarray(data, dtype=dtype)
data[mask] = fill_value
data = duck_array_ops.where_method(data, ~mask, fill_value)
else:
data = np.asarray(data)

Expand Down
13 changes: 13 additions & 0 deletions xarray/tests/test_variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -2560,6 +2560,19 @@ def test_masked_array(self):
assert_array_equal(expected, actual)
assert np.dtype(float) == actual.dtype

original = np.ma.MaskedArray([1.0, 2.0], mask=[True, False])
original.flags.writeable = False
expected = [np.nan, 2.0]
actual = as_compatible_data(original)
assert_array_equal(expected, actual)
assert np.dtype(float) == actual.dtype

# GH2377
actual = Variable(dims=tuple(), data=np.ma.masked)
expected = Variable(dims=tuple(), data=np.nan)
assert_array_equal(expected, actual)
assert actual.dtype == expected.dtype

@pytest.mark.filterwarnings("ignore:Converting non-nanosecond")
def test_datetime(self):
expected = np.datetime64("2000-01-01")
Expand Down