Search code examples
dataframepython-xarray

Xarray KeyError: the index is unsorted or non-unique


I have an Xarray, which contains Sentinel-2 satellite images. Based on this Stackstac example, I am trying to crop my AOI using loc:

aoi = da.loc[..., y_utm + m_buffer:y_utm - m_buffer, x_utm - m_buffer:x_utm + m_buffer]

This is producing an error:

keyerror: "cannot represent labeled-based slice indexer for coordinate 'time' with a slice over integer positions; the index is unsorted or non-unique

I have tried sorting the index:

da = da.sortby('time')

...and also dropping any duplicates in time:

_, index = np.unique(da['time'], return_index=True)
da.isel(time=index)

But these do not resolve the error. Any help appreciated.

Update: printing out the time values, they are sorted, but there is also one missing value. How can I remove this?

 '2022-11-22T18:04:02.003000000' '2022-11-25T18:13:57.149000000'
 '2022-11-27T18:04:01.065000000' '2022-11-30T18:13:56.264000000'
 '2022-12-10T18:13:54.658000000' '2022-12-15T18:13:57.458000000'
 '2022-12-17T18:04:00.671000000'                           'NaT']

Solution

  • I got the same error with netcdf data from CMEMS in xarray. My solution was to drop duplicate time values. You may try a similar approach and try dropping NaTs:

    nc = xr.open_dataset(*url to data*)    
    nc = nc.dropna(dim='time')
    

    The documentation is here.