Xarray Pandas dayofyear使用leap年产生了错误的尺寸

时间:2019-05-03 17:41:21

标签: python pandas datetime python-xarray

我正在尝试将每小时气候数据汇总为使用xarray的年度文件的每日平均值。但是,我将它们用“水年”而不是日历年(从10月1日到9月30日)分开。

当我尝试使用'groupby(.dayofyear)'方法时,它在水上年份的起始日期或结束日期均落在实际leap年内时会产生不正确的'dayofyear'维度。

例如,对于跨越leap日的2000年水年(10/01/1999-09/30/2000),生成的代码将生成一个dayofyear尺寸,大小为365,而不是366。进行2001年水年时(2000年1月10日-2001年9月30日),它没有跨越leap日,它会产生不正确的尺寸尺寸366,而不是365。

我确定我可以从头开始构建数组,但希望有一个内置函数或其他简单的方法来解决此问题。

new_array['TMEAN'] = d['T2'].groupby('XTIME.dayofyear').mean(dim='Time')

1 个答案:

答案 0 :(得分:1)

当然,这是使用resample进行操作的简短示例。我们将首先构建一个与您的结构相似的DataArray。

import numpy as np
import pandas as pd
import xarray as xr

ntimes = 24000
time = np.arange(ntimes)
times = xr.DataArray(pd.date_range('2000', periods=ntimes, freq='H'))
xtime = xr.DataArray(times, dims=['time'], coords=[time], name='XTIME')
da = xr.DataArray(np.random.random(ntimes), dims=['time'], coords=[time], name='T2')
da['XTIME'] = xtime

此处da由具有整数坐标的名为'time'的维度索引。它还有一个称为'XTIME'的日期时间坐标:

<xarray.DataArray 'T2' (time: 24000)>
array([0.285948, 0.046776, 0.0814  , ..., 0.47595 , 0.241202, 0.453325])
Coordinates:
  * time     (time) int64 0 1 2 3 4 5 6 ... 23994 23995 23996 23997 23998 23999
    XTIME    (time) datetime64[ns] 1999-01-01 ... 2001-09-26T23:00:00

要使用resample,我们需要使'XTIME'成为DataArray中的维度坐标,而不是'time'。一种有用的方法是swap_dims

result = da.swap_dims({'time': 'XTIME'}).resample(XTIME='D').mean()

result如下所示:

<xarray.DataArray 'T2' (XTIME: 1000)>
array([0.487798, 0.422622, 0.497371, ..., 0.487836, 0.500065, 0.482849])
Coordinates:
  * XTIME    (XTIME) datetime64[ns] 1999-01-01 1999-01-02 ... 2001-09-26

然后,如果我正确理解了这些内容,则将它们分为“水年”就只是将result设置为子集的问题,例如:

water_year_2000 = result.sel(XTIME=slice('1999-10-01', '2000-09-30'))