我有一个xarray,它使用open_dataset从服务器读取服务器的月平均表面温度,且array_code_times = False,因为xarray无法识别日历类型.

经过一些操作后,我得到了表面温度(‘ts’)和时间(‘T’)的数据集my_dataset:

Dimensions: (T: 1800)

Coordinates:

* T (T) float32 0.5 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5 10.5 11.5 ...

Data variables:

ts (T) float64 246.6 247.9 250.7 260.1 271.9 281.1 283.3 280.5 ...

“ T”具有以下属性:

Attributes:

pointwidth: 1.0

calendar: 360

gridtype: 0

units: months since 0300-01-01

我想获取此月度数据并计算年度平均值,但是由于T坐标不是日期时间,因此无法使用xarray.Dataset.resample.现在,我只是在转换为一个numpy数组,但是我想要一种保存xarray数据集的方法.

我目前的基本方法:

temps = np.mean(np.array(my_dataset['ts']).reshape(-1,12),axis=1)

years = np.array(my_dataset['T'])/12

我感谢您的帮助,即使最好的方法是重新定义时间坐标以使用重采样.

编辑:

询问如何创建xarray,它是通过以下操作完成的:

import numpy as np

import matplotlib.pyplot as plt

import xarray as xr

filename = 'http://strega.ldeo.columbia.edu:81/CMIP5/.byScenario/.abrupt4xCO2/.atmos/.mon/.ts/ACCESS1-0/r1i1p1/.ts/dods'

ds = xr.open_dataset(filename,decode_times=False)

zonal_mean = ds.mean(dim='lon')

arctic_only = zonal.where(zonal['lat'] >= 60).dropna('lat')

weights = np.cos(np.deg2rad(arctic['lat']))/np.sum(np.cos(np.deg2rad(arctic['lat'])))

my_dataset = (arctic_only * weights).sum(dim='lat')

解决方法:

这是一个非常普遍的问题,尤其是来自INGRID的数据集. xarray无法解码其单位为“自…以来的月份”的日期的原因是由于底层的netcdf4-python库拒绝解析此类日期. netcdf4-python github issue中对此进行了讨论

The problem with time units such as “months” is that they are not well defined. In contrast to days, hours, etc. the length of a month depends on the calendar used and even varies between different months.

不幸的是,尽管有歧义,INGRID拒绝接受这一事实,并继续使用“月”作为其默认单位.因此,现在INGRID与xarray / python-netcdf4之间存在令人沮丧的不兼容性.

无论如何,这是一种无需离开xarray即可完成您想要的工作的技巧

# create new coordinates for month and year

ds.coords['month'] = np.ceil(ds['T'] % 12).astype('int')

ds.coords['year'] = (ds['T'] // 12).astype('int')

# calculate monthly climatology

ds_clim = ds.groupby('month').mean(dim='T')

# calculate annual mean

ds_am = ds.groupby('year').mean(dim='T')

标签:python-datetime,python-xarray,python,numpy

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐