Is it possible to load a netCDF with xarray, and change one of the coordinates?

I am having an issue with a netCDF I have, in which a coordinate named band with values in integers, actually means a time period (the original data were a bunch of ENVI files loaded with rioxarray, and then persisted as netCDF).

I want to map it as a datetime field, but I am struggling to make it work. Any suggestions?

I have originally posted it on stack exchange with a screenshot.

You defined a new coordinate but it also created a new dimension instead of applying it to the “band” dimension. Initially I suggested Dataset.swap_dims() and Dataset.drop_dims(), but I didn’t get them to work. Actually Dataset.assign_dimension() should work to assign new time series values to the band dimension.

1 Like

Something like this should work:

time = pd.date_range("1982-01-01", periods=408, frequ="M")
ds.assign_coords(band=("band",time)).rename(band="time")

The way it works is that you should specify to xarray what is the dimension to this new coordinate. Then you rename the coordinate and dimension to time.

Here below I give you my reproducible code snippet for my example

import xarray as xr
import pandas as pd
import numpy as np

n = 408
ds = xr.Dataset(dict(param=("band", np.random.randn(n))), coords=dict(band=np.arange(n)))

time = pd.date_range("1982-01-01", periods=n, freq="M")
ds = ds.assign_coords(band=("band",time)).rename(band="time")

ds

Which returns the following:

image

1 Like