xarray.DataArray.assign_coords¶
-
DataArray.
assign_coords
(coords=None, **coords_kwargs)¶ Assign new coordinates to this object.
Returns a new object with all the original data in addition to the new coordinates.
- Parameters
coords (
dict
, optional) – A dict where the keys are the names of the coordinates with the new values to assign. If the values are callable, they are computed on this object and assigned to new coordinate variables. If the values are not callable, (e.g. aDataArray
, scalar, or array), they are simply assigned. A new coordinate can also be defined and attached to an existing dimension using a tuple with the first element the dimension name and the second element the values for this new coordinate.**coords_kwargs (optional) – The keyword arguments form of
coords
. One ofcoords
orcoords_kwargs
must be provided.
- Returns
assigned (
same type as caller
) – A new object with the new coordinates in addition to the existing data.
Examples
Convert 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)> array([0.5488135 , 0.71518937, 0.60276338, 0.54488318]) Coordinates: * lon (lon) int64 358 359 0 1 >>> da.assign_coords(lon=(((da.lon + 180) % 360) - 180)) <xarray.DataArray (lon: 4)> array([0.5488135 , 0.71518937, 0.60276338, 0.54488318]) Coordinates: * lon (lon) int64 -2 -1 0 1
The function also accepts dictionary arguments:
>>> da.assign_coords({"lon": (((da.lon + 180) % 360) - 180)}) <xarray.DataArray (lon: 4)> array([0.5488135 , 0.71518937, 0.60276338, 0.54488318]) Coordinates: * lon (lon) int64 -2 -1 0 1
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)> array([0.5488135 , 0.71518937, 0.60276338, 0.54488318]) Coordinates: * lon (lon) int64 358 359 0 1 lon_2 (lon) int64 300 289 0 1
Note that the same result can also be obtained with a dict e.g.
>>> _ = da.assign_coords({"lon_2": ("lon", lon_2)})
Notes
Since
coords_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 sameassign_coords
is possible, but you cannot reference other variables created within the sameassign_coords
call.See also