Add an array to this dataset. Multiple arrays can be added at the same time, in which case each of the following operations is applied to the respective value. If key is dict-like, update all variables in the dataset one by one with the given value at the given locat
(
self, key: Hashable | Iterable[Hashable] | Mapping, value: Any
)
| 1372 | raise ValueError(f"Unsupported key-type {type(key)}") |
| 1373 | |
| 1374 | def __setitem__( |
| 1375 | self, key: Hashable | Iterable[Hashable] | Mapping, value: Any |
| 1376 | ) -> None: |
| 1377 | """Add an array to this dataset. |
| 1378 | Multiple arrays can be added at the same time, in which case each of |
| 1379 | the following operations is applied to the respective value. |
| 1380 | |
| 1381 | If key is dict-like, update all variables in the dataset |
| 1382 | one by one with the given value at the given location. |
| 1383 | If the given value is also a dataset, select corresponding variables |
| 1384 | in the given value and in the dataset to be changed. |
| 1385 | |
| 1386 | If value is a ` |
| 1387 | from .dataarray import DataArray`, call its `select_vars()` method, rename it |
| 1388 | to `key` and merge the contents of the resulting dataset into this |
| 1389 | dataset. |
| 1390 | |
| 1391 | If value is a `Variable` object (or tuple of form |
| 1392 | ``(dims, data[, attrs])``), add it to this dataset as a new |
| 1393 | variable. |
| 1394 | """ |
| 1395 | from xarray.core.dataarray import DataArray |
| 1396 | |
| 1397 | if utils.is_dict_like(key): |
| 1398 | # check for consistency and convert value to dataset |
| 1399 | value = self._setitem_check(key, value) |
| 1400 | # loop over dataset variables and set new values |
| 1401 | processed = [] |
| 1402 | for name, var in self.items(): |
| 1403 | try: |
| 1404 | var[key] = value[name] |
| 1405 | processed.append(name) |
| 1406 | except Exception as e: |
| 1407 | if processed: |
| 1408 | raise RuntimeError( |
| 1409 | "An error occurred while setting values of the" |
| 1410 | f" variable '{name}'. The following variables have" |
| 1411 | f" been successfully updated:\n{processed}" |
| 1412 | ) from e |
| 1413 | else: |
| 1414 | raise e |
| 1415 | |
| 1416 | elif utils.hashable(key): |
| 1417 | if isinstance(value, Dataset): |
| 1418 | raise TypeError( |
| 1419 | "Cannot assign a Dataset to a single key - only a DataArray or Variable " |
| 1420 | "object can be stored under a single key." |
| 1421 | ) |
| 1422 | self.update({key: value}) |
| 1423 | |
| 1424 | elif utils.iterable_of_hashable(key): |
| 1425 | keylist = list(key) |
| 1426 | if len(keylist) == 0: |
| 1427 | raise ValueError("Empty list of variables to be set") |
| 1428 | if len(keylist) == 1: |
| 1429 | self.update({keylist[0]: value}) |
| 1430 | else: |
| 1431 | if len(keylist) != len(value): |
nothing calls this directly
no test coverage detected