Apply a function to each data variable in this dataset Parameters ---------- func : callable Function which can be called in the form `func(x, *args, **kwargs)` to transform each DataArray `x` in this dataset into another DataArray.
( # type: ignore[override]
self,
func: Callable,
keep_attrs: bool | None = None,
args: Iterable[Any] = (),
**kwargs: Any,
)
| 381 | ) |
| 382 | |
| 383 | def map( # type: ignore[override] |
| 384 | self, |
| 385 | func: Callable, |
| 386 | keep_attrs: bool | None = None, |
| 387 | args: Iterable[Any] = (), |
| 388 | **kwargs: Any, |
| 389 | ) -> Dataset: |
| 390 | """Apply a function to each data variable in this dataset |
| 391 | |
| 392 | Parameters |
| 393 | ---------- |
| 394 | func : callable |
| 395 | Function which can be called in the form `func(x, *args, **kwargs)` |
| 396 | to transform each DataArray `x` in this dataset into another |
| 397 | DataArray. |
| 398 | keep_attrs : bool | None, optional |
| 399 | If True, both the dataset's and variables' attributes (`attrs`) will be |
| 400 | copied from the original objects to the new ones. If False, the new dataset |
| 401 | and variables will be returned without copying the attributes. |
| 402 | args : iterable, optional |
| 403 | Positional arguments passed on to `func`. |
| 404 | **kwargs : Any |
| 405 | Keyword arguments passed on to `func`. |
| 406 | |
| 407 | Returns |
| 408 | ------- |
| 409 | applied : Dataset |
| 410 | Resulting dataset from applying ``func`` to each data variable. |
| 411 | |
| 412 | Examples |
| 413 | -------- |
| 414 | >>> da = xr.DataArray(np.random.randn(2, 3)) |
| 415 | >>> ds = xr.Dataset({"foo": da, "bar": ("x", [-1, 2])}) |
| 416 | >>> ds |
| 417 | <xarray.Dataset> Size: 64B |
| 418 | Dimensions: (dim_0: 2, dim_1: 3, x: 2) |
| 419 | Dimensions without coordinates: dim_0, dim_1, x |
| 420 | Data variables: |
| 421 | foo (dim_0, dim_1) float64 48B 1.764 0.4002 0.9787 2.241 1.868 -0.9773 |
| 422 | bar (x) int64 16B -1 2 |
| 423 | >>> ds.map(np.fabs) |
| 424 | <xarray.Dataset> Size: 64B |
| 425 | Dimensions: (dim_0: 2, dim_1: 3, x: 2) |
| 426 | Dimensions without coordinates: dim_0, dim_1, x |
| 427 | Data variables: |
| 428 | foo (dim_0, dim_1) float64 48B 1.764 0.4002 0.9787 2.241 1.868 0.9773 |
| 429 | bar (x) float64 16B 1.0 2.0 |
| 430 | """ |
| 431 | |
| 432 | # Copied from xarray.Dataset so as not to call type(self), which causes problems (see https://github.com/xarray-contrib/datatree/issues/188). |
| 433 | # TODO Refactor xarray upstream to avoid needing to overwrite this. |
| 434 | if keep_attrs is None: |
| 435 | keep_attrs = _get_keep_attrs(default=True) |
| 436 | variables = { |
| 437 | k: maybe_wrap_array(v, func(v, *args, **kwargs)) |
| 438 | for k, v in self.data_vars.items() |
| 439 | } |
| 440 | if keep_attrs: |
nothing calls this directly
no test coverage detected