Python xarray – Converting NetCDF from 0 to 360 to -180 to 180

netcdfpythonrioxarrayxarray

I've got an ERA5 NetCDF that's in 0 to 360 and I'd like to convert it to -180 to 180 before saving it off as a raster. I've got the current workflow set up, but am unsure of how to switch the longs.

with xr.open_dataset(nc_fp, mask_and_scale=True, decode_times=True) as src:
    ds = src.sel(time="2020-01-01").max('time')
    ds.rio.write_crs("epsg:4326", inplace=True)
    ds.rio.to_raster('test.tif')

Best Answer

This method worked:

with xr.open_dataset(nc_fp, mask_and_scale=True, decode_times=True) as src:
    ds = src.sel(time="2020-01-01").max('time')
    ds.rio.write_crs("epsg:4326", inplace=True)
    ds.coords['longitude'] = (ds.coords['longitude'] + 180) % 360 - 180
    ds = ds.sortby(ds.longitude)
    ds.rio.to_raster('test.tif')
Related Question