xarray 无法直接将 xarray.Dataset 转换为 numpy 数组

xarray cannot directly convert an xarray.Dataset into a numpy array

我在尝试使用 xarray 将数据集转换为数组时遇到似乎无法解决的错误。我遇到这个问题是因为我试图向 netcdf 文件添加时间维度(打开 netcdf,添加所有数据都相同的时间戳,保存 netcdf)。

import xarray as xr
import pandas as pd

scriptpath = os.path.dirname(os.path.abspath(__file__))

outputfile = scriptpath + '\20210629_deadgrass.aus.nc'

times= pd.to_datetime(str(yesterday.strftime('%Y%m%d')))
time_da = xr.Dataset({"time": times})

arr = xr.open_dataset(outputfile)
ds = arr.to_array()
dst = ds.expand_dims(time=time_da) #errors here

我收到的错误是

Exception has occurred: TypeError
cannot directly convert an xarray.Dataset into a numpy array. Instead, create an xarray.DataArray first, either with indexing on the Dataset or by invoking the `to_array()` method.
  File "Z:\UpdateAussieGRASS.py", line 101, in <module>
    dst = ds.expand_dims(time=time_da)

我似乎无法弄清楚我在倒数第二行的 to_array() 做错了什么。 to_array() 的例子是 here. Autogenerated documentation is here.

ds 已经是 xarray.DataArray。错误发生在这一行:

dst = ds.expand_dims(time=time_da) #errors here

因为 dsDataArraytime_da 不是。这应该有效:

dst = ds.expand_dims(time=time_da.to_array())