'Xarray's idxmax function returns an error when trying to assign the variable id corresponding with maximum pixel value across raster stack

I have an xarray dataarray with dimensions time, lat and lon. The time dimension represents periods of n days, e.g. 5 days, 10 days, 15 days etc. I am trying to create a new raster with pixel values equal to the variable id along the time dimension (n days) for the maximum pixel value within the data array stack.

I'm using the code:

corrs_da.idxmax(dim='time',skipna=True,fill_value=None)

And I get the error: KeyError: 'Dimension "time" does not have coordinates'

Here is an example of the input dataarray:

data array example



Solution 1:[1]

Think you need to run

corrs_da = corrs_da.rename({"variable": "time"})

before doing corrs_da.idxmax(dim='time',skipna=True,fill_value=None).

Not completely sure why though, since corrs_da.time.coords does seem to indicate that time has coordinates.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bert Coerver