Skip to content
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

Fix dataarray drop attrs #10030

Open
wants to merge 3 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: 10 additions & 3 deletions xarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -7575,6 +7575,13 @@ def drop_attrs(self, *, deep: bool = True) -> Self:
-------
DataArray
"""
return (
self._to_temp_dataset().drop_attrs(deep=deep).pipe(self._from_temp_dataset)
)
if not deep:
for k in list(self.attrs):
del self.attrs[k]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That changes the data array inplace which is something we try to avoid.
Can you return a copy instead while leaving the original one intact?

return self
else:
return (
self._to_temp_dataset()
.drop_attrs(deep=deep)
.pipe(self._from_temp_dataset)
)
5 changes: 4 additions & 1 deletion xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -2991,8 +2991,11 @@ def test_assign_attrs(self) -> None:

def test_drop_attrs(self) -> None:
# Mostly tested in test_dataset.py, but adding a very small test here
da = DataArray([], attrs=dict(a=1, b=2))
coord_ = xr.DataArray([], attrs=dict(d=3, e=4))
da = DataArray([], attrs=dict(a=1, b=2)).assign_coords(dict(coord_=coord_))
assert da.drop_attrs().attrs == {}
assert da.drop_attrs().coord_.attrs == {}
assert da.drop_attrs(deep=False).coord_.attrs == dict(d=3, e=4)

@pytest.mark.parametrize(
"func", [lambda x: x.clip(0, 1), lambda x: np.float64(1.0) * x, np.abs, abs]
Expand Down
Loading