Skip to content

propagate attrs on coords in Dataset.map #10602

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
13 changes: 12 additions & 1 deletion xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -6880,11 +6880,22 @@ def map(
k: maybe_wrap_array(v, func(v, *args, **kwargs))
for k, v in self.data_vars.items()
}
coord_vars, indexes = merge_coordinates_without_align(
[v.coords for v in variables.values()]
)
coords = Coordinates._construct_direct(coords=coord_vars, indexes=indexes)

if keep_attrs:
for k, v in variables.items():
v._copy_attrs_from(self.data_vars[k])

for k, v in coords.items():
if k not in self.coords:
continue
v._copy_attrs_from(self.coords[k])

attrs = self.attrs if keep_attrs else None
return type(self)(variables, attrs=attrs)
return type(self)(variables, coords=coords, attrs=attrs)

def apply(
self,
Expand Down
32 changes: 32 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -6128,6 +6128,38 @@ def scale(x, multiple=1):
expected = data.drop_vars("time") # time is not used on a data var
assert_equal(expected, actual)

def test_map_coords_attrs(self) -> None:
ds = xr.Dataset(
{
"a": (
["x", "y", "z"],
np.arange(24).reshape(3, 4, 2),
{"attr1": "value1"},
),
"b": ("y", np.arange(4), {"attr2": "value2"}),
},
coords={
"x": ("x", np.array([-1, 0, 1]), {"attr3": "value3"}),
"z": ("z", list("ab"), {"attr4": "value4"}),
},
)

def func(arr):
if "y" not in arr.dims:
return arr

# drop attrs from coords
return arr.mean(dim="y").drop_attrs()

expected = ds.mean(dim="y", keep_attrs=True)
actual = ds.map(func, keep_attrs=True)

assert_identical(actual, expected)
assert actual["x"].attrs

ds["x"].attrs["y"] = "x"
assert ds["x"].attrs != actual["x"].attrs

def test_apply_pending_deprecated_map(self) -> None:
data = create_test_data()
data.attrs["foo"] = "bar"
Expand Down
11 changes: 11 additions & 0 deletions xarray/tests/test_weighted.py
Original file line number Diff line number Diff line change
Expand Up @@ -770,6 +770,17 @@ def test_weighted_operations_keep_attr_da_in_ds(operation):
assert data.a.attrs == result.a.attrs


def test_weighted_mean_keep_attrs_ds():
weights = DataArray(np.random.randn(2))
data = Dataset(
{"a": (["dim_0", "dim_1"], np.random.randn(2, 2), dict(attr="data"))},
coords={"dim_1": ("dim_1", ["a", "b"], {"attr1": "value1"})},
)

result = data.weighted(weights).mean(dim="dim_0", keep_attrs=True)
assert data.coords["dim_1"].attrs == result.coords["dim_1"].attrs


@pytest.mark.parametrize("operation", ("sum_of_weights", "sum", "mean", "quantile"))
@pytest.mark.parametrize("as_dataset", (True, False))
def test_weighted_bad_dim(operation, as_dataset):
Expand Down
Loading