微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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())

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。