Xarray时间变量中的更改单位

问题描述

我有一个nc文件,其中时间变量不能被xarray.open_dataset()解码,因为单位在'days_since_Jan11900'中,这是days变量的完整信息:

<xarray.DataArray 'days' (time: 87600)>
array([679352.,679353.,679354.,...,766949.,766950.,766951.])
Dimensions without coordinates: time
Attributes:
    units:      days_since_Jan11900
    long_name:  calendar_days

我已经用ds = xr.open_dataset('path/tmax_bcc-csm1-1.nc',decode_times = False)打开了文件,但是现在我想将nc文件的单位更改为Python可以轻松解码的内容。就我而言,时间单位是从0000年1月1日开始的几天。最终,这将使我的分析变得更加容易。

我该怎么做?

解决方法

要解码时间,xarray会搜索包含units形式的"{time_unit} since {reference_date}"属性的变量。在您的情况下,我将覆盖DataArray上的units属性,然后手动解码时间:

ds.days.attrs["units"] = "days since 0000-01-01"
result = xr.decode_cf(ds)

我要说明的一个警告是,我怀疑您的参考日期无效,因此解码时间可能会引发错误。