Skip to content

Change data type of coordinates #5209

Answered by keewis
maawoo asked this question in Q&A
Apr 22, 2021 · 1 comments · 1 reply
Discussion options

You must be logged in to vote

unfortunately the canonical method (astype) indeed does not allow converting the coords. For data variables it would have been possible to specify a dict that maps names to dtypes (this is missing from the Dataset.astype documentation). To work around that, we can use assign:

In [8]: ds = xr.Dataset({"a": ("x", [1.3, 6.2])}, coords={"x": [0, 1]})
   ...: ds
Out[8]: 
<xarray.Dataset>
Dimensions:  (x: 2)
Coordinates:
  * x        (x) int64 0 1
Data variables:
    a        (x) float64 1.3 6.2

In [9]: ds.assign(x=lambda ds: ds.x.astype(float))
Out[9]: 
<xarray.Dataset>
Dimensions:  (x: 2)
Coordinates:
  * x        (x) float64 0.0 1.0
Data variables:
    a        (x) float64 1.3 6.2

I think e…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@maawoo
Comment options

Answer selected by maawoo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants