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

问题描述

在使用 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自动生成的文档是 here

解决方法

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

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

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

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