Assign new data variables to a Dataset, returning a new object with all the original variables in addition to the new ones. Parameters ---------- variables : mapping of hashable to Any Mapping from variables names to the new values. If the new values
(
self,
variables: Mapping[Any, Any] | None = None,
**variables_kwargs: Any,
)
| 7034 | return self.map(func, keep_attrs, args, **kwargs) |
| 7035 | |
| 7036 | def assign( |
| 7037 | self, |
| 7038 | variables: Mapping[Any, Any] | None = None, |
| 7039 | **variables_kwargs: Any, |
| 7040 | ) -> Self: |
| 7041 | """Assign new data variables to a Dataset, returning a new object |
| 7042 | with all the original variables in addition to the new ones. |
| 7043 | |
| 7044 | Parameters |
| 7045 | ---------- |
| 7046 | variables : mapping of hashable to Any |
| 7047 | Mapping from variables names to the new values. If the new values |
| 7048 | are callable, they are computed on the Dataset and assigned to new |
| 7049 | data variables. If the values are not callable, (e.g. a DataArray, |
| 7050 | scalar, or array), they are simply assigned. |
| 7051 | **variables_kwargs |
| 7052 | The keyword arguments form of ``variables``. |
| 7053 | One of variables or variables_kwargs must be provided. |
| 7054 | |
| 7055 | Returns |
| 7056 | ------- |
| 7057 | ds : Dataset |
| 7058 | A new Dataset with the new variables in addition to all the |
| 7059 | existing variables. |
| 7060 | |
| 7061 | Notes |
| 7062 | ----- |
| 7063 | Since ``kwargs`` is a dictionary, the order of your arguments may not |
| 7064 | be preserved, and so the order of the new variables is not well |
| 7065 | defined. Assigning multiple variables within the same ``assign`` is |
| 7066 | possible, but you cannot reference other variables created within the |
| 7067 | same ``assign`` call. |
| 7068 | |
| 7069 | The new assigned variables that replace existing coordinates in the |
| 7070 | original dataset are still listed as coordinates in the returned |
| 7071 | Dataset. |
| 7072 | |
| 7073 | See Also |
| 7074 | -------- |
| 7075 | pandas.DataFrame.assign |
| 7076 | |
| 7077 | Examples |
| 7078 | -------- |
| 7079 | >>> x = xr.Dataset( |
| 7080 | ... { |
| 7081 | ... "temperature_c": ( |
| 7082 | ... ("lat", "lon"), |
| 7083 | ... 20 * np.random.rand(4).reshape(2, 2), |
| 7084 | ... ), |
| 7085 | ... "precipitation": (("lat", "lon"), np.random.rand(4).reshape(2, 2)), |
| 7086 | ... }, |
| 7087 | ... coords={"lat": [10, 20], "lon": [150, 160]}, |
| 7088 | ... ) |
| 7089 | >>> x |
| 7090 | <xarray.Dataset> Size: 96B |
| 7091 | Dimensions: (lat: 2, lon: 2) |
| 7092 | Coordinates: |
| 7093 | * lat (lat) int64 16B 10 20 |