Assign new coordinates to this object. Returns a new object with all the original data in addition to the new coordinates. Parameters ---------- coords : mapping of dim to coord, optional A mapping whose keys are the names of the coordinates and
(
self,
coords: Mapping | None = None,
**coords_kwargs: Any,
)
| 518 | return {k: v(self) if callable(v) else v for k, v in kwargs.items()} |
| 519 | |
| 520 | def assign_coords( |
| 521 | self, |
| 522 | coords: Mapping | None = None, |
| 523 | **coords_kwargs: Any, |
| 524 | ) -> Self: |
| 525 | """Assign new coordinates to this object. |
| 526 | |
| 527 | Returns a new object with all the original data in addition to the new |
| 528 | coordinates. |
| 529 | |
| 530 | Parameters |
| 531 | ---------- |
| 532 | coords : mapping of dim to coord, optional |
| 533 | A mapping whose keys are the names of the coordinates and values are the |
| 534 | coordinates to assign. The mapping will generally be a dict or |
| 535 | :class:`Coordinates`. |
| 536 | |
| 537 | * If a value is a standard data value — for example, a ``DataArray``, |
| 538 | scalar, or array — the data is simply assigned as a coordinate. |
| 539 | |
| 540 | * If a value is callable, it is called with this object as the only |
| 541 | parameter, and the return value is used as new coordinate variables. |
| 542 | |
| 543 | * A coordinate can also be defined and attached to an existing dimension |
| 544 | using a tuple with the first element the dimension name and the second |
| 545 | element the values for this new coordinate. |
| 546 | |
| 547 | **coords_kwargs : optional |
| 548 | The keyword arguments form of ``coords``. |
| 549 | One of ``coords`` or ``coords_kwargs`` must be provided. |
| 550 | |
| 551 | Returns |
| 552 | ------- |
| 553 | assigned : same type as caller |
| 554 | A new object with the new coordinates in addition to the existing |
| 555 | data. |
| 556 | |
| 557 | Examples |
| 558 | -------- |
| 559 | Convert `DataArray` longitude coordinates from 0-359 to -180-179: |
| 560 | |
| 561 | >>> da = xr.DataArray( |
| 562 | ... np.random.rand(4), |
| 563 | ... coords=[np.array([358, 359, 0, 1])], |
| 564 | ... dims="lon", |
| 565 | ... ) |
| 566 | >>> da |
| 567 | <xarray.DataArray (lon: 4)> Size: 32B |
| 568 | array([0.5488135 , 0.71518937, 0.60276338, 0.54488318]) |
| 569 | Coordinates: |
| 570 | * lon (lon) int64 32B 358 359 0 1 |
| 571 | >>> da.assign_coords(lon=(((da.lon + 180) % 360) - 180)) |
| 572 | <xarray.DataArray (lon: 4)> Size: 32B |
| 573 | array([0.5488135 , 0.71518937, 0.60276338, 0.54488318]) |
| 574 | Coordinates: |
| 575 | * lon (lon) int64 32B -2 -1 0 1 |
| 576 | |
| 577 | The function also accepts dictionary arguments: |
nothing calls this directly
no test coverage detected