簡體   English   中英

使用新維度將 xarray.Dataset 的多個變量合並為一個變量

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

我有一個包含多個變量的數據集,這些變量的名稱類似於t1t2t3等。我正在尋找一個簡單的 function 通過使用額外的維度將它們全部合並到一個變量t中。

基本上我想要在下面的 MWE 中得到的 output:

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

這幾乎可以實現我想要的,但我很確定已經有一個 xarray function 了。 或者至少我相信它可以用更少的行來完成。

您正在尋找to_array方法:

ds["t"] = ds.to_array(dim="α")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM