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

Add a .drop_attrs method #8258

Merged
merged 25 commits into from
Jul 11, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
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
10 changes: 10 additions & 0 deletions xarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -7146,3 +7146,13 @@ def to_dask_dataframe(
# this needs to be at the end, or mypy will confuse with `str`
# https://mypy.readthedocs.io/en/latest/common_issues.html#dealing-with-conflicting-names
str = utils.UncachedAccessor(StringAccessor["DataArray"])

def drop_attrs(self) -> Self:
"""
Removes all attributes from the DataArray.
"""
max-sixty marked this conversation as resolved.
Show resolved Hide resolved
self = self.copy()

self.attrs = {}
dcherian marked this conversation as resolved.
Show resolved Hide resolved

return self
16 changes: 16 additions & 0 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -10338,3 +10338,19 @@ def resample(
restore_coord_dims=restore_coord_dims,
**indexer_kwargs,
)

def drop_attrs(self) -> Self:
"""
Removes all attributes from the Dataset and its variables.
"""
# Remove attributes from the dataset
self = self._replace(attrs={})

# Remove attributes from each variable in the dataset
for var in self.variables:
# variables don't have a `._replace` method, so we copy and then remove. If
# we added a `._replace` method, we could use that instead.
self[var] = self[var].copy()
dcherian marked this conversation as resolved.
Show resolved Hide resolved
self[var].attrs = {}
Copy link
Contributor

Choose a reason for hiding this comment

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

To my understanding this should wipe the attrs of the index_vars of the original object?

xarray/xarray/core/dataset.py

Lines 1361 to 1365 in e8be4bb

for k, v in self._variables.items():
if k in index_vars:
variables[k] = index_vars[k]
else:
variables[k] = v._copy(deep=deep, data=data.get(k), memo=memo)

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Atm an Index can't have attrs, at least on main testing ds.indexes['y'].attrs fails.

I added an explicit test for the coords. Lmk if you have anything else we could do for the index...

Copy link
Member

@benbovy benbovy Oct 9, 2023

Choose a reason for hiding this comment

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

I wonder if the invariant checks will pass when testing this on a Dataset with a multi-index.

It might be problematic to copy coordinates variables individually when they have a common index and especially when they all wrap exactly the same index object in their ._data attribute (like in the case of a PandasMultiIndex). A safer approach would be to handle the indexed variables with something like this:

new_variables = {}

for idx, idx_vars in self.xindexes.group_by_index():
    # copy each coordinate variable of an index and drop their attrs
    temp_variables = {k: v.copy() for k, v in idx_vars.items()}
    for v in temp_variables.values():
        v.attrs = {}
    # maybe re-wrap the index object in new coordinate variables
    new_variables.update(idx.create_variables(temp_variables))

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Thanks, done. I don't think I've done it elegantly, but I'm a bit out of my depth and so won't try and solve perfectly on this pass...


return self
5 changes: 5 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -2955,6 +2955,11 @@ def test_assign_attrs(self) -> None:
assert_identical(new_actual, expected)
assert actual.attrs == {"a": 1, "b": 2}

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))
assert da.drop_attrs().attrs == {}

@pytest.mark.parametrize(
"func", [lambda x: x.clip(0, 1), lambda x: np.float64(1.0) * x, np.abs, abs]
)
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 @@ -4355,6 +4355,38 @@ def test_assign_attrs(self) -> None:
assert_identical(new_actual, expected)
assert actual.attrs == dict(a=1, b=2)

def test_drop_attrs(self) -> None:
# Simple example
ds = Dataset().assign_attrs(a=1, b=2)
original = ds.copy()
expected = Dataset()
result = ds.drop_attrs()
assert_identical(result, expected)

# Doesn't change original
assert_identical(ds, original)

# Example with variables and coords with attrs, check they're dropped too
var = Variable("x", [1, 2, 3], attrs=dict(x=1, y=2))
idx = IndexVariable("y", [1, 2, 3], attrs=dict(c=1, d=2))
ds = Dataset(dict(var1=var), coords=dict(y=idx)).assign_attrs(a=1, b=2)
assert ds.coords["y"].attrs != {}

original = ds.copy(deep=True)
result = ds.drop_attrs()

assert result.attrs == {}
assert result["x"].attrs == {}
assert result["y"].attrs == {}
assert list(result.data_vars) == list(ds.data_vars)
assert list(result.coords) == list(ds.coords)

# Doesn't change original
assert_identical(ds, original)
# Specifically test that the attrs on the coords are still there. (The index
# can't currently contain `attrs`, so we can't test those.)
assert ds.coords["y"].attrs != {}

def test_assign_multiindex_level(self) -> None:
data = create_test_multiindex()
with pytest.raises(ValueError, match=r"cannot drop or update.*corrupt.*index "):
Expand Down
Loading