I've a NetCDF file in which the variables are stored in 0 to 360-degrees longitude. I would like to convert it to -180 to 180 degrees. This should be a rather straightforward task but for some reason I can't seem to make some of the examples given in the tutorial work out.
ds = xr.open_dataset(file_)
>ds
<xarray.Dataset>
Dimensions: (lev: 1, lon: 720, time: 1460)
Coordinates:
* lon (lon) float64 0.0 0.5 1.0 1.5 2.0 2.5 ... -2.5 -2.0 -1.5 -1.0 -0.5
* lev (lev) float32 1.0
* time (time) datetime64[ns] 2001-01-01 ... 2001-12-31T18:00:00
Data variables:
V (time, lev, lon) float32 13.281297 11.417505 ... -19.312767
I try using the help of Dataset.assign_coord
ds.V.assign_coords(lon=((ds.V.lon + 180) % 360 - 180))
#gives me a new array with lon -180 to 180
ds['V'] = ds.V.assign_coords(lon=((ds.V.lon + 180) % 360 - 180))
# didn't modify the V for some reason?
So, assign_coords worked but setting the variable back to Dataset doesn't work. After many tries, I figured to directly modify the coordinates "lon" because they're linked to the Datavariable "V" via dictionary.
ds.coords['lon'] = (ds.coords['lon'] + 180) % 360 - 180
#solves the problem!
Second Problem I encountered is in sorting my data variable according to the above-modified longitudes. I tried
ds['V'] = ds.V.sortby(ds.lon)
>ds.V
# the array is not sorted according to -180 to 180 values
But when I sort the dataset and assign it, it works.
ds = ds.sortby(ds.lon) # now my dataset is sorted to -180 to 180 degrees lon
It would be very helpful for my understanding of xarrays if someone can point out why my first approach for both problems are not working?