【问题标题】:averaging 2 decades of data on 6 hourly timestep using netcdf data and python使用 netcdf 数据和 python 在 6 小时时间步长上平均 2 个十年的数据
【发布时间】:2019-09-23 15:42:00
【问题描述】:

我有 2 个十年的空间可变风数据,每 6 小时记录一次。我需要在每六个小时的时间间隔内平均 2 个十年的数据,所以我最终得到 365 * 4 个时间步长。数据为 netcdf 格式。

数据如下所示:

import xarray as xr
filename = 'V-01011999-01012019.nc'
ds = xr.open_dataset(filename)

print(ds)
<xarray.Dataset>
Dimensions:  (lat: 8, lon: 7, time: 29221)
Coordinates:
  * lat      (lat) float32 -2.5 -5.0 -7.5 -10.0 -12.5 -15.0 -17.5 -20.0
  * lon      (lon) float32 130.0 132.5 135.0 137.5 140.0 142.5 145.0
  * time     (time) datetime64[ns] 1999-01-01 1999-01-01T06:00:00 .. 2019-01-01
Data variables:
vwnd     (time, lat, lon) float32 ...

#remove feb 29 from records
ds = ds.sel(time=~((ds.time.dt.month == 2) & (ds.time.dt.day == 29)))

我已经能够按一年中的一天进行分组,以获得一年中一天的 2 个十年平均值。

tsavg = ds.groupby('time.dayofyear').mean('time')

print(tsavg)
<xarray.Dataset>
Dimensions:    (dayofyear: 366, lat: 8, lon: 7)
Coordinates:
  * lat        (lat) float32 -2.5 -5.0 -7.5 -10.0 -12.5 -15.0 -17.5 -20.0
  * lon        (lon) float32 130.0 132.5 135.0 137.5 140.0 142.5 145.0
  * dayofyear  (dayofyear) int64 1 2 3 4 5 6 7 8 ... 360 361 362 363 364 365 366
Data variables:
    vwnd       (dayofyear, lat, lon) float32 -2.61605 -1.49012 ... -0.959997

我真正想要的是长度为 365 * 4(一天 4 x 6 小时间隔)的时间坐标,每个时间步长是该时间步长过去 20 年的平均值。 此外,由于某种原因 tsavg.dayofyear 长度仍然是 366,即使我删除了 2 月 29 日。 我无法申请或关注this post 的答案。 我已经广泛研究了groupby 资源并尝试了很多东西,但我无法弄清楚。我正在寻求一些编码方面的帮助。

【问题讨论】:

  • 有方法ds.groupby('time.hourofyear').mean('time')吗?如果没有,您可以编写一种方法,根据一年中的小时值对数据进行平均。

标签: python-xarray


【解决方案1】:

确实没有一个很好的记录方法来做到这一点。另请注意dayofyear may not be exactly what you expect it to be

代替能够在多个级别使用groupby(例如,请参阅this answer,了解如何执行类似于您在pandas 中所要求的操作),这在xarray 中尚不可用,这是一种相当干净的方式解决此类问题的方法是为分组定义一个新坐标,该坐标代表数据集中每个时间的“一年中的时间”。

在您的情况下,您希望按“一年中的小时”(即匹配月、日和小时)进行分组。为此,您可以创建一个字符串数组,它们基本上只是时间坐标中日期的字符串表示形式,并带有删除的年份:

ds['hourofyear'] = xr.DataArray(ds.indexes['time'].strftime('%m-%d %H'), coords=ds.time.coords)
result = ds.groupby('hourofyear').mean('time')

【讨论】:

  • 谢谢,这正是我要找的!
猜你喜欢
  • 2018-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-07
  • 2014-10-16
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多