xarray.Dataset.assign (original) (raw)

Dataset.assign(variables=None, **variables_kwargs)[source]#

Assign new data variables to a Dataset, returning a new object with all the original variables in addition to the new ones.

Parameters:

Returns:

ds (Dataset) – A new Dataset with the new variables in addition to all the existing variables.

Notes

Since kwargs is a dictionary, the order of your arguments may not be preserved, and so the order of the new variables is not well defined. Assigning multiple variables within the same assign is possible, but you cannot reference other variables created within the same assign call.

The new assigned variables that replace existing coordinates in the original dataset are still listed as coordinates in the returned Dataset.

Examples

x = xr.Dataset( ... { ... "temperature_c": ( ... ("lat", "lon"), ... 20 * np.random.rand(4).reshape(2, 2), ... ), ... "precipitation": (("lat", "lon"), np.random.rand(4).reshape(2, 2)), ... }, ... coords={"lat": [10, 20], "lon": [150, 160]}, ... ) x <xarray.Dataset> Size: 96B Dimensions: (lat: 2, lon: 2) Coordinates:

Where the value is a callable, evaluated on dataset:

x.assign(temperature_f=lambda x: x.temperature_c * 9 / 5 + 32) <xarray.Dataset> Size: 128B Dimensions: (lat: 2, lon: 2) Coordinates:

Alternatively, the same behavior can be achieved by directly referencing an existing dataarray:

x.assign(temperature_f=x["temperature_c"] * 9 / 5 + 32) <xarray.Dataset> Size: 128B Dimensions: (lat: 2, lon: 2) Coordinates: