|
36 | 36 | HybridMappingProxy,
|
37 | 37 | _default,
|
38 | 38 | either_dict_or_kwargs,
|
| 39 | + maybe_wrap_array, |
39 | 40 | )
|
40 | 41 | from xarray.core.variable import Variable
|
41 | 42 |
|
@@ -235,6 +236,65 @@ def _replace(
|
235 | 236 | inplace=inplace,
|
236 | 237 | )
|
237 | 238 |
|
| 239 | + def map( |
| 240 | + self, |
| 241 | + func: Callable, |
| 242 | + keep_attrs: bool | None = None, |
| 243 | + args: Iterable[Any] = (), |
| 244 | + **kwargs: Any, |
| 245 | + ) -> Dataset: |
| 246 | + """Apply a function to each data variable in this dataset |
| 247 | +
|
| 248 | + Parameters |
| 249 | + ---------- |
| 250 | + func : callable |
| 251 | + Function which can be called in the form `func(x, *args, **kwargs)` |
| 252 | + to transform each DataArray `x` in this dataset into another |
| 253 | + DataArray. |
| 254 | + keep_attrs : bool or None, optional |
| 255 | + If True, both the dataset's and variables' attributes (`attrs`) will be |
| 256 | + copied from the original objects to the new ones. If False, the new dataset |
| 257 | + and variables will be returned without copying the attributes. |
| 258 | + args : iterable, optional |
| 259 | + Positional arguments passed on to `func`. |
| 260 | + **kwargs : Any |
| 261 | + Keyword arguments passed on to `func`. |
| 262 | +
|
| 263 | + Returns |
| 264 | + ------- |
| 265 | + applied : Dataset |
| 266 | + Resulting dataset from applying ``func`` to each data variable. |
| 267 | +
|
| 268 | + Examples |
| 269 | + -------- |
| 270 | + >>> da = xr.DataArray(np.random.randn(2, 3)) |
| 271 | + >>> ds = xr.Dataset({"foo": da, "bar": ("x", [-1, 2])}) |
| 272 | + >>> ds |
| 273 | + <xarray.Dataset> |
| 274 | + Dimensions: (dim_0: 2, dim_1: 3, x: 2) |
| 275 | + Dimensions without coordinates: dim_0, dim_1, x |
| 276 | + Data variables: |
| 277 | + foo (dim_0, dim_1) float64 1.764 0.4002 0.9787 2.241 1.868 -0.9773 |
| 278 | + bar (x) int64 -1 2 |
| 279 | + >>> ds.map(np.fabs) |
| 280 | + <xarray.Dataset> |
| 281 | + Dimensions: (dim_0: 2, dim_1: 3, x: 2) |
| 282 | + Dimensions without coordinates: dim_0, dim_1, x |
| 283 | + Data variables: |
| 284 | + foo (dim_0, dim_1) float64 1.764 0.4002 0.9787 2.241 1.868 0.9773 |
| 285 | + bar (x) float64 1.0 2.0 |
| 286 | + """ |
| 287 | + |
| 288 | + # Copied from xarray.Dataset so as not to call type(self), which causes problems (see datatree GH188). |
| 289 | + # TODO Refactor xarray upstream to avoid needing to overwrite this. |
| 290 | + # TODO This copied version will drop all attrs - the keep_attrs stuff should be re-instated |
| 291 | + variables = { |
| 292 | + k: maybe_wrap_array(v, func(v, *args, **kwargs)) |
| 293 | + for k, v in self.data_vars.items() |
| 294 | + } |
| 295 | + # return type(self)(variables, attrs=attrs) |
| 296 | + return Dataset(variables) |
| 297 | + |
238 | 298 |
|
239 | 299 | class DataTree(
|
240 | 300 | NamedNode,
|
|
0 commit comments