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.
(
self,
func: Callable,
keep_attrs: bool | None = None,
args: Iterable[Any] = (),
**kwargs: Any,
)
| 6932 | ) |
| 6933 | |
| 6934 | def map( |
| 6935 | self, |
| 6936 | func: Callable, |
| 6937 | keep_attrs: bool | None = None, |
| 6938 | args: Iterable[Any] = (), |
| 6939 | **kwargs: Any, |
| 6940 | ) -> Self: |
| 6941 | """Apply a function to each data variable in this dataset |
| 6942 | |
| 6943 | Parameters |
| 6944 | ---------- |
| 6945 | func : callable |
| 6946 | Function which can be called in the form `func(x, *args, **kwargs)` |
| 6947 | to transform each DataArray `x` in this dataset into another |
| 6948 | DataArray. |
| 6949 | keep_attrs : bool or None, optional |
| 6950 | If True, both the dataset's and variables' attributes (`attrs`) will be |
| 6951 | copied from the original objects to the new ones. If False, the new dataset |
| 6952 | and variables will be returned without copying the attributes. |
| 6953 | args : iterable, optional |
| 6954 | Positional arguments passed on to `func`. |
| 6955 | **kwargs : Any |
| 6956 | Keyword arguments passed on to `func`. |
| 6957 | |
| 6958 | Returns |
| 6959 | ------- |
| 6960 | applied : Dataset |
| 6961 | Resulting dataset from applying ``func`` to each data variable. |
| 6962 | |
| 6963 | Examples |
| 6964 | -------- |
| 6965 | >>> da = xr.DataArray(np.random.randn(2, 3)) |
| 6966 | >>> ds = xr.Dataset({"foo": da, "bar": ("x", [-1, 2])}) |
| 6967 | >>> ds |
| 6968 | <xarray.Dataset> Size: 64B |
| 6969 | Dimensions: (dim_0: 2, dim_1: 3, x: 2) |
| 6970 | Dimensions without coordinates: dim_0, dim_1, x |
| 6971 | Data variables: |
| 6972 | foo (dim_0, dim_1) float64 48B 1.764 0.4002 0.9787 2.241 1.868 -0.9773 |
| 6973 | bar (x) int64 16B -1 2 |
| 6974 | >>> ds.map(np.fabs) |
| 6975 | <xarray.Dataset> Size: 64B |
| 6976 | Dimensions: (dim_0: 2, dim_1: 3, x: 2) |
| 6977 | Dimensions without coordinates: dim_0, dim_1, x |
| 6978 | Data variables: |
| 6979 | foo (dim_0, dim_1) float64 48B 1.764 0.4002 0.9787 2.241 1.868 0.9773 |
| 6980 | bar (x) float64 16B 1.0 2.0 |
| 6981 | """ |
| 6982 | from xarray.core.dataarray import DataArray |
| 6983 | |
| 6984 | if keep_attrs is None: |
| 6985 | keep_attrs = _get_keep_attrs(default=True) |
| 6986 | variables = { |
| 6987 | k: maybe_wrap_array(v, func(v, *args, **kwargs)) |
| 6988 | for k, v in self.data_vars.items() |
| 6989 | } |
| 6990 | # Convert non-DataArray values to DataArrays |
| 6991 | variables = { |