xarray - 使用 groupby 按一年中的每一天的气候每小时 netCDF 数据进行分组

ale*_*xtc 5 python netcdf pandas python-xarray

我有一年多地理范围内每小时的 netCDF 气候数据,例如从2017-01-01T00:00:002017-12-31T23:00:00

<xarray.Dataset>
Dimensions:    (latitude: 106, longitude: 193, time: 8760)
Coordinates:
  * latitude   (latitude) float32 -39.2 -39.149525 ... -33.950478 -33.9
  * longitude  (longitude) float32 140.8 140.84792 140.89584 ... 149.95209 150.0
  * time       (time) datetime64[ns] 2017-01-01 ... 2017-12-31T23:00:00
Data variables:
    T_SFC      (time, latitude, longitude) float32 dask.array<shape=(8760, 106, 193), chunksize=(744, 106, 193)>
Attributes:
    creationTime:        1525708833
    creationTimeString:  Mon May  7 09:00:32 PDT 2018
    Conventions:         COARDS
Run Code Online (Sandbox Code Playgroud)

正如它所说,数据具有三个坐标(纬度、经度和时间)和一个变量是每小时温度。

我的代码:

import xarray as xr
mds_temp_path = '../Archive/*/IDV71000_VIC_T_SFC.nc'    # netCDF
mds_temp = xr.open_mfdataset(mds_temp_path)    # open netCDF and read into a dataset object

print(mds_temp.groupby('time.dayofyear').mean('time'))
Run Code Online (Sandbox Code Playgroud)

我得到了什么:

<xarray.Dataset>
Dimensions:    (dayofyear: 365, latitude: 106, longitude: 193)
Coordinates:
  * latitude   (latitude) float32 -39.2 -39.149525 ... -33.950478 -33.9
  * longitude  (longitude) float32 140.8 140.84792 140.89584 ... 149.95209 150.0
  * dayofyear  (dayofyear) int64 1 2 3 4 5 6 7 8 ... 359 360 361 362 363 364 365
Data variables:
    T_SFC   (dayofyear, latitude, longitude) float64 dask.array<shape=(365, 106, 193), chunksize=(1, 106, 193)>
Run Code Online (Sandbox Code Playgroud)

我希望实现的目标是能够获得每天的平均温度值,例如生成的数据集中的时间坐标为“2017-01-01”、“2017-01-02”、“2017-01-03” ”、……、“2017-12-31”,而不是 1、2、3、……、365。

jha*_*man 6

您应该使用该resample方法而不是groupby

mds_temp.resample(time='1D').mean()
Run Code Online (Sandbox Code Playgroud)

这些概念在文档的时间序列数据部分中有更全面的描述:http://xarray.pydata.org/en/stable/time-series.html#resampling-and-grouped-operations