如何在使用 xarray 加载 NETCDF 文件时解码时间变量
How to decode the time variable while using xarray to load a NETCDF file
我有一个 netcdf 文件,给出了从 1948 年到 2008 年的月降水量值。时间变量的格式如下:
float time(time) ;
time:units = "months since 1948-01-01 00:00:00" ;
time:time_origin = "01-JAN-1948:00:00:00" ;
当我尝试使用 Xarray 使用以下命令打开数据集时
ds=xr.open_dataset("C:/Users/vsri/Downloads/prcp_monthly_1948-2008.nc")
我收到以下错误
ValueError: unable to decode time units 'months since 1948-01-01 00:00:00' with the default calendar. Try opening your dataset with decode_times=False.
如果我使用 decode_Times=False 参数,时间变量会分配一个浮点值(如下所示)
Coordinates:
* longitude (longitude) float32 0.25 0.75 1.25 1.75 ... 358.75 359.25 359.75
* latitude (latitude) float32 -89.75 -89.25 -88.75 ... 88.75 89.25 89.75
* z (z) float32 0.0
* time (time) float32 0.0 1.0 2.0 3.0 4.0 ... 728.0 729.0 730.0 731.0
我不想使用 decode_Times=False 因为我不能再在数据集上使用 xarray 的重采样功能。
有人可以指导我如何确保 xarray 读取具有正确时间戳而不是浮点数的数据集吗?
感谢您更新评论。在你的情况下,由于你的数据有规律的频率,我建议通过创建你自己的时间坐标来解决这个问题 pandas.date_range
:
import pandas as pd
import xarray as xr
ds = xr.open_dataset("C:/Users/vsri/Downloads/prcp_monthly_1948-2008.nc", decode_times=False)
units, reference_date = ds.time.attrs['units'].split('since')
ds['time'] = pd.date_range(start=reference_date, periods=ds.sizes['time'], freq='MS')
这将为每个月的第一天创建一个日期数组,从 1948 年 1 月 1 日开始到适当的月数之后结束。
我有一个 netcdf 文件,给出了从 1948 年到 2008 年的月降水量值。时间变量的格式如下:
float time(time) ;
time:units = "months since 1948-01-01 00:00:00" ;
time:time_origin = "01-JAN-1948:00:00:00" ;
当我尝试使用 Xarray 使用以下命令打开数据集时
ds=xr.open_dataset("C:/Users/vsri/Downloads/prcp_monthly_1948-2008.nc")
我收到以下错误
ValueError: unable to decode time units 'months since 1948-01-01 00:00:00' with the default calendar. Try opening your dataset with decode_times=False.
如果我使用 decode_Times=False 参数,时间变量会分配一个浮点值(如下所示)
Coordinates:
* longitude (longitude) float32 0.25 0.75 1.25 1.75 ... 358.75 359.25 359.75
* latitude (latitude) float32 -89.75 -89.25 -88.75 ... 88.75 89.25 89.75
* z (z) float32 0.0
* time (time) float32 0.0 1.0 2.0 3.0 4.0 ... 728.0 729.0 730.0 731.0
我不想使用 decode_Times=False 因为我不能再在数据集上使用 xarray 的重采样功能。
有人可以指导我如何确保 xarray 读取具有正确时间戳而不是浮点数的数据集吗?
感谢您更新评论。在你的情况下,由于你的数据有规律的频率,我建议通过创建你自己的时间坐标来解决这个问题 pandas.date_range
:
import pandas as pd
import xarray as xr
ds = xr.open_dataset("C:/Users/vsri/Downloads/prcp_monthly_1948-2008.nc", decode_times=False)
units, reference_date = ds.time.attrs['units'].split('since')
ds['time'] = pd.date_range(start=reference_date, periods=ds.sizes['time'], freq='MS')
这将为每个月的第一天创建一个日期数组,从 1948 年 1 月 1 日开始到适当的月数之后结束。