Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
max-sixty committed Oct 14, 2023
1 parent 1e0fc8d commit 10ab123
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
27 changes: 23 additions & 4 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -10342,15 +10342,34 @@ def resample(
def drop_attrs(self) -> Self:
"""
Removes all attributes from the Dataset and its variables.
Returns
-------
Dataset
"""
# 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()
self[var].attrs = {}
# variables don't have a `._replace` method, so we copy and then remove
# attrs. If we added a `._replace` method, we could use that instead.
if var not in self.indexes:
self[var] = self[var].copy()
self[var].attrs = {}

new_idx_variables = {}

# Not sure this is the most elegant way of doing this, but it works.
# (Contributions welcome for a more general "map over all variables, including
# indexes" approach.)
for idx, idx_vars in self.xindexes.group_by_index():
# copy each coordinate variable of an index and drop their attrs
temp_idx_variables = {k: v.copy() for k, v in idx_vars.items()}
for v in temp_idx_variables.values():
v.attrs = {}
# maybe re-wrap the index object in new coordinate variables
new_idx_variables.update(idx.create_variables(temp_idx_variables))
self = self.assign(**new_idx_variables)

return self
9 changes: 7 additions & 2 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -4366,10 +4366,15 @@ def test_drop_attrs(self) -> None:
# Doesn't change original
assert_identical(ds, original)

# Example with variables and coords with attrs, check they're dropped too
# Example with variables and coords with attrs, and a multiindex. (arguably
# should have used a canonical dataset with all the features we're should
# support...)
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)
mx = xr.Coordinates.from_pandas_multiindex(
pd.MultiIndex.from_tuples([(1, 2), (3, 4)], names=["d", "e"]), "z"
)
ds = Dataset(dict(var1=var), coords=dict(y=idx, z=mx)).assign_attrs(a=1, b=2)
assert ds.coords["y"].attrs != {}

original = ds.copy(deep=True)
Expand Down

0 comments on commit 10ab123

Please sign in to comment.