Stream: python-questions
Topic: xarray change coordinate to variable?
Stephen Yeager (Mar 18 2021 at 18:08):
I want to change 'time' from a coordinate to a Data variable in an xarray Dataset. How do I do it?
Anderson Banihirwe (Mar 18 2021 at 18:21):
There's a .reset_coords()
: https://xarray.pydata.org/en/stable/generated/xarray.Dataset.reset_coords.html method on both dataset and datarray objects.
In [3]: ds Out[3]: <xarray.Dataset> Dimensions: (time: 36, x: 275, y: 205) Coordinates: * time (time) object 1980-09-16 12:00:00 ... 1983-08-17 00:00:00 xc (y, x) float64 ... yc (y, x) float64 ... Dimensions without coordinates: x, y Data variables: Tair (time, y, x) float64 ...
Invoking this method on a non-dimension coordinate (those without the *
) works:
In [10]: ds.reset_coords(["xc"]) Out[10]: <xarray.Dataset> Dimensions: (time: 36, x: 275, y: 205) Coordinates: * time (time) object 1980-09-16 12:00:00 ... 1983-08-17 00:00:00 yc (y, x) float64 ... Dimensions without coordinates: x, y Data variables: Tair (time, y, x) float64 ... xc (y, x) float64 ...
However, if your coordinate is a dimension coordinate, xarray doesn't allow resetting this coordinate to a regular variable:
In [11]: ds.reset_coords(["time"]) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-11-53667df9faf0> in <module> ----> 1 ds.reset_coords(["time"]) ~/opt/miniconda/envs/playground/lib/python3.9/site-packages/xarray/core/dataset.py in reset_coords(self, names, drop) 1586 bad_coords = set(names) & set(self.dims) 1587 if bad_coords: -> 1588 raise ValueError( 1589 "cannot remove index coordinates with reset_coords: %s" % bad_coords 1590 ) ValueError: cannot remove index coordinates with reset_coords: {'time'}
Anderson Banihirwe (Mar 18 2021 at 18:29):
I'm curious... what do you hope to accomplish once you've set the time
coordinate to a regular variable?
Stephen Yeager (Mar 18 2021 at 18:45):
Thanks! That worked. This is for the SMYLE-analysis repo, for which there is a need for initialized prediction Datasets that are dimensioned as follows: (Y,L,M,...) where Y is start time, L is lead time, and M is ensemble member. It's useful to have the original "time" coordinate converted to a data variable that acquires dimensions (Y,L). You can have a look after I upload the finished notebook.
Matt Long (Mar 18 2021 at 18:47):
I think we prototyped an intake-esm approach to reading DPLE datasets
Deepak Cherian (Mar 18 2021 at 19:02):
One place to check these kinds of questions: https://xarray.pydata.org/en/latest/howdoi.html
Stephen Yeager (Mar 18 2021 at 21:25):
I think we prototyped an intake-esm approach to reading DPLE datasets
This will be good to revisit for SMYLE-analysis. For now, I'm finding it helpful to learn how to do the necessary data manipulations.
Last updated: Jan 30 2022 at 12:01 UTC