xarray.Dataset.assign_coords (original) (raw)

Dataset.assign_coords(coords=None, **coords_kwargs)[source]#

Assign new coordinates to this object.

Returns a new object with all the original data in addition to the new coordinates.

Parameters:

Returns:

assigned (same type as caller) – A new object with the new coordinates in addition to the existing data.

Examples

Convert DataArray longitude coordinates from 0-359 to -180-179:

da = xr.DataArray( ... np.random.rand(4), ... coords=[np.array([358, 359, 0, 1])], ... dims="lon", ... ) da <xarray.DataArray (lon: 4)> Size: 32B array([0.5488135 , 0.71518937, 0.60276338, 0.54488318]) Coordinates:

The function also accepts dictionary arguments:

da.assign_coords({"lon": (((da.lon + 180) % 360) - 180)}) <xarray.DataArray (lon: 4)> Size: 32B array([0.5488135 , 0.71518937, 0.60276338, 0.54488318]) Coordinates:

New coordinate can also be attached to an existing dimension:

lon_2 = np.array([300, 289, 0, 1]) da.assign_coords(lon_2=("lon", lon_2)) <xarray.DataArray (lon: 4)> Size: 32B array([0.5488135 , 0.71518937, 0.60276338, 0.54488318]) Coordinates:

Note that the same result can also be obtained with a dict e.g.

_ = da.assign_coords({"lon_2": ("lon", lon_2)})

Note the same method applies to Dataset objects.

Convert Dataset longitude coordinates from 0-359 to -180-179:

temperature = np.linspace(20, 32, num=16).reshape(2, 2, 4) precipitation = 2 * np.identity(4).reshape(2, 2, 4) ds = xr.Dataset( ... data_vars=dict( ... temperature=(["x", "y", "time"], temperature), ... precipitation=(["x", "y", "time"], precipitation), ... ), ... coords=dict( ... lon=(["x", "y"], [[260.17, 260.68], [260.21, 260.77]]), ... lat=(["x", "y"], [[42.25, 42.21], [42.63, 42.59]]), ... time=pd.date_range("2014-09-06", periods=4), ... reference_time=pd.Timestamp("2014-09-05"), ... ), ... attrs=dict(description="Weather-related data"), ... ) ds <xarray.Dataset> Size: 360B Dimensions: (x: 2, y: 2, time: 4) Coordinates: lon (x, y) float64 32B 260.2 260.7 260.2 260.8 lat (x, y) float64 32B 42.25 42.21 42.63 42.59