Skip to main content
 首页 » 编程设计

python之使用 xarray 中的 'year + month' 组合计算平均值

2024年11月24日9duanxz

我有一个包含 5 年(2011 年至 2015 年)每日数据的 netcdf 文件。我想在 Python 中使用 XArray 计算数据的月平均值。

netcdf file:////test/Combined.nc { 
  dimensions: 
    latitude = 681; 
    longitude = 841; 
    time = 1826; 
  variables: 
    double latitude(latitude=681); 
      :_FillValue = NaN; // double 
      :name = "latitude"; 
      :long_name = "latitude"; 
      :units = "degrees_north"; 
      :standard_name = "latitude"; 
 
    double longitude(longitude=841); 
      :_FillValue = NaN; // double 
      :name = "longitude"; 
      :long_name = "longitude"; 
      :units = "degrees_east"; 
      :standard_name = "longitude"; 
 
    long time(time=1826); 
      :name = "time"; 
      :long_name = "time"; 
      :standard_name = "time"; 
      :units = "days since 2011-01-01 00:00:00"; 
      :calendar = "proleptic_gregorian"; 
 
    float PET(time=1826, latitude=681, longitude=841); 
      :_FillValue = -999.0f; // float 
      :name = "PET"; 
      :long_name = "Potential evapotranspiration"; 
      :units = "mm"; 
      :standard_name = "PET";       
 
  :var_name = "PET"; 
} 

我尝试做的是使用 groupby 来计算月平均值:

import numpy as np 
import xarray as xr 
 
ds = xr.open_dataset("c:\\test\\Combined.nc") 
ds_avg = ds.PET.groupby('time.month').mean(dim='time') 
ds_avg.to_netcdf("C:\\test\\Combined_avg.nc")  

但上面代码的问题是吐出一个具有合并月平均值的文件(从 2011 年到 2015 年)。这意味着我在结果文件中有 12 个月的时间。那不是我想做的。我想计算 2011 年 1 月、2011 年 2 月、2011 年 3 月到 2015 年 12 月的月平均值,以便在结果文件中得到 12 * 5 个月。因此,这意味着 groupby 不应发生在“time.month”上,而应发生在“time.year:time.month”上。我该怎么做?

谢谢

请您参考如下方法:

你应该使用resample doc以一个月的频率。然后:

ds_avg = ds.resample('1M').mean() 

如果您对任何其他类似(简单)操作感兴趣,请查看我们为 ERA-NUTS dataset 设置的笔记本。 .

另一个使用另一个数据集的例子:

<xarray.Dataset> 
Dimensions:    (bnds: 2, latitude: 61, longitude: 91, time: 218) 
Coordinates: 
  * longitude  (longitude) float32 -22.5 -21.75 -21.0 -20.25 ... 43.5 44.25 45.0 
  * latitude   (latitude) float32 72.0 71.25 70.5 69.75 ... 28.5 27.75 27.0 
  * time       (time) datetime64[ns] 2000-01-16T15:00:00 ... 2018-01-01T03:00:00 
Dimensions without coordinates: bnds 
Data variables: 
    time_bnds  (time, bnds) datetime64[ns] ... 
    ssrdc      (time, latitude, longitude) float64 ... 
    ssrd       (time, latitude, longitude) float64 ... 

然后应用重采样:

In [13]: d.resample(time = '1Y').mean()                                                                                            
Out[13]:  
<xarray.Dataset> 
Dimensions:    (latitude: 61, longitude: 91, time: 19) 
Coordinates: 
  * time       (time) datetime64[ns] 2000-12-31 2001-12-31 ... 2018-12-31 
  * longitude  (longitude) float32 -22.5 -21.75 -21.0 -20.25 ... 43.5 44.25 45.0 
  * latitude   (latitude) float32 72.0 71.25 70.5 69.75 ... 28.5 27.75 27.0 
Data variables: 
    ssrdc      (time, latitude, longitude) float64 5.033e+05 ... 1.908e+05 
    ssrd       (time, latitude, longitude) float64 4.229e+05 ... 1.909e+05