I have an Xarray.Dataset with the coordinates 'range' and 'time'.
How can I access the values of coordinate named 'range' to add a static scalar like 200 for example?
# imports
import xarray as xr
import numpy as np
import pandas as pd
time = pd.date_range("2006-02-21", freq="s", periods=4)
print(time)
# create a small xarray
da = xr.DataArray(np.random.randn(4, 4), dims=("range", "time"), coords={"time": time})
# add a coordinate to this array with shifts to apply to each rows
da=da.assign_coords(range=('range', [1.56,5.233,10.98,17.43]))
print(da)
The aimed result for 'range' should be this:
Coordinates:
* range (range) float64 201.56 205.233 210.98 217.43
This is not working:
da.range = da.range + 200
You are very close.
You will need to use assign_coords
again to update the Xarray DataArray with the new range.
To perform a calculation, you need to access the array by using da.range.values
.
Try this:
da = da.assign_coords(range = da.range.values + 200)
print(da)
<xarray.DataArray (range: 4, time: 4)>
array([[ 1.841789, 0.488786, 0.2098 , -0.653168],
[-0.84231 , -0.972959, -1.077549, -0.310968],
[-0.740298, 1.628546, -0.373804, -0.391335],
[-0.564398, -1.487397, 2.735653, 0.019958]])
Coordinates:
* time (time) datetime64[ns] 2006-02-21 ... 2006-02-21T00:00:03
* range (range) float64 201.6 205.2 211.0 217.4