Merging several variables of an xarray.Dataset into one using a new dimension
Question:
I have a Dataset with several variables that named something like t1
, t2
, t3
, etc. I’m looking for a simple function to merge them all into one variable t
through the use an extra dimension.
Basically I want the output that I’m getting in the MWE below:
import xarray as xr
import numpy as np
ds = xr.Dataset({"t1": (("y", "x"), np.random.rand(6).reshape(2, 3)),
"t2": (("y", "x"), np.random.rand(6).reshape(2, 3)),
"t3": (("y", "x"), np.random.rand(6).reshape(2, 3)),
}, coords={"y": [0, 1], "x": [10, 20, 30]},)
t_list = []
for i, v in enumerate(ds.variables.keys()):
if v.startswith("t"):
t_list.append(ds[v].expand_dims("α").assign_coords(α=[i]))
ds = ds.drop(v)
ds["t"] = xr.concat(t_list, dim="α")
This pretty much achieves what I want, but I’m pretty sure there’s an xarray function for it already. Or at least I’m convinced it can be done in fewer lines.
Answers:
You are looking for the to_array
method:
ds["t"] = ds.to_array(dim="α")
I have a Dataset with several variables that named something like t1
, t2
, t3
, etc. I’m looking for a simple function to merge them all into one variable t
through the use an extra dimension.
Basically I want the output that I’m getting in the MWE below:
import xarray as xr
import numpy as np
ds = xr.Dataset({"t1": (("y", "x"), np.random.rand(6).reshape(2, 3)),
"t2": (("y", "x"), np.random.rand(6).reshape(2, 3)),
"t3": (("y", "x"), np.random.rand(6).reshape(2, 3)),
}, coords={"y": [0, 1], "x": [10, 20, 30]},)
t_list = []
for i, v in enumerate(ds.variables.keys()):
if v.startswith("t"):
t_list.append(ds[v].expand_dims("α").assign_coords(α=[i]))
ds = ds.drop(v)
ds["t"] = xr.concat(t_list, dim="α")
This pretty much achieves what I want, but I’m pretty sure there’s an xarray function for it already. Or at least I’m convinced it can be done in fewer lines.
You are looking for the to_array
method:
ds["t"] = ds.to_array(dim="α")