error when trying to swap dimensions in xarray

16 Views Asked by At

I have an xarray Dataset with the following information:

xarray.Dataset
Dimensions: index: 68
Coordinates:
index (index) int64
0 1 2 3 4 5 6 ... 62 63 64 65 66 67 
Data variables:
YEAR (index) float64
nan 1.957e+03 ... 2.023e+03
ANN (index) float64
nan -4.24 -1.27 ... 3.03 4.18 2.04
AUT (index) float64
nan -2.52 -2.97 ... 0.34 1.93 0.74
WIN (index) float64 
nan -0.68 -0.92 ... 0.57 0.03 -0.11
SPR
(index)
float64
nan -3.55 1.42 ... 2.8 4.25 0.25
SUM (index) float64
nan -2.52 1.12 ... 3.25 3.83 nan
Indexes: (1)
Attributes: (0)

I'd like to create dates with cftime_range, and replace the current coordinate and dimensions with this:

dates = xr.cftime_range(start='1956', periods=68, freq='YS', calendar='noleap')
dates

However, when I try to swap dimensions and set the coordinates to be 'time', I end up with the following error:

dsn = dsn.set_coords('time').swap_dims({'index': 'time'})
dsn


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [92], in <module>
      1 # dsn["time"] = ("time", dates)
      2 # dsn.swap_dims({"index":"time"})
----> 3 dsn = dsn.set_coords('time').swap_dims({'index': 'time'})
      5 dsn

File /glade/work/mberdahl/miniconda/envs/pangeo/lib/python3.9/site-packages/xarray/core/dataset.py:3829, in Dataset.swap_dims(self, dims_dict, **dims_kwargs)
   3824         raise ValueError(
   3825             f"cannot swap from dimension {k!r} because it is "
   3826             "not an existing dimension"
   3827         )
   3828     if v in self.variables and self.variables[v].dims != (k,):
-> 3829         raise ValueError(
   3830             f"replacement dimension {v!r} is not a 1D "
   3831             f"variable along the old dimension {k!r}"
   3832         )
   3834 result_dims = {dims_dict.get(dim, dim) for dim in self.dims}
   3836 coord_names = self._coord_names.copy()

ValueError: replacement dimension 'time' is not a 1D variable along the old dimension 'index'

Any thoughts?

0

There are 0 best solutions below