I try to replace two coordinates with the same length in a xarray.Dataset by using one coordinate for both of them. I do not care about the old coordinates or its values; I simply want to replace them. Is there any convenient method for this?
import xarray as xr
ds = xr.Dataset({
"a": ("a_coord", [0, 1, 2]),
"b": ("b_coord", [50, 10, 20]),
"a_coord": [4, 8, 9],
"b_coord": [3, 1, 4],
"new_coord": [0, 1, 2],
})
# Get rid of a_coord and b_coord and replace both with new_coord, so a and b
# have new_coord as coordinate.
# But how?
I tried rename
, but it returns a conflict error (since new_coord already exists).
ds.rename({
"a_coord": "new_coord",
"b_coord": "new_coord",
})
Do I have to assign the new coordinate explicitly to each data variable that was depended on one of the old coordinates? Since I have many data variables (not just a and b) and other coordinates, this could become messy.
You need to reset index first:
ds.reset_index(['a_coord', 'b_coord'], drop = True, inplace = True)
ds['a']= ds.a.rename({'a_coord': 'new_coord'})
ds['b']= ds.b.rename({'b_coord': 'new_coord'})