简体   繁体   中英

Merging several variables of an xarray.Dataset into one using a new dimension

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="α")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM