Nctoolkit 对相同数据重复选择

问题描述

我正在查看非洲的月降水数据,并希望将数据分解为子区域。有没有办法在同一个 ds 上进行多项选择/裁剪? 这是我的代码

fn1 = 'cru_monthly_africa.nc'
ds1 = nt.open_data(fn1)
#Selecting a specific variable,time period and area and then calculating the field mean for each month:
ds1.select(variables = "pre")
ds1.select(years = range(1981,2018))
ds1.crop(lon = [20,27],lat = [-35,-33.5])
ds1.spatial_mean()
ds1.tmean("month")
#Export to xarray
ds1csc_xr = ds1.to_xarray()

#Next region:
ds1.select(variables = "pre")
ds1.select(years = range(1981,2018))
ds1.crop(lon = [17,20],-31])
ds1.spatial_mean()
ds1.tmean("month")
#Export to xarray
ds1swc_xr = ds1.to_xarray()

我现在想做完全相同但使用一组不同的纬度和经度坐标并将其写入单独的 xarray(即每个子区域都是它自己的 xarray)。如果我尝试重复脚本中的代码但更改输出 xr 的坐标和名称,它只会为我提供与第一个 xr 相同的值。 我刚开始使用 python 和 nctoolkit 处理带有气候数据的 netcdf 文件,希望得到任何指导。

解决方法

您想修改代码,以便在裁剪之前复制 ds1 数据集。现在您正在对 ds1 进行两次裁剪。

fn1 = 'cru_monthly_africa.nc'
ds1 = nt.open_data(fn1)
#Selecting a specific variable,time period and area and then calculating 
#the field mean for each month:
ds1.select(variables = "pre")
ds1.select(years = range(1981,2018))
ds2 = ds1.copy()
ds1.crop(lon = [20,27],lat = [-35,-33.5])
ds1.spatial_mean()
ds1.tmean("month")
#Export to xarray
ds1csc_xr = ds1.to_xarray()

#Next region:
ds2.crop(lon = [17,20],-31])
ds2.spatial_mean()
ds2.tmean("month")
#Export to xarray
ds2swc_xr = ds2.to_xarray()

或者,您可以将第二次裁剪替换为:

#Next region:
ds1 = nt.open_data(fn1)
ds1.select(variables = "pre")
ds1.select(years = range(1981,2018))
ds1.crop(lon = [17,-31])
ds1.spatial_mean()
ds1.tmean("month")
#Export to xarray
ds1swc_xr = ds1.to_xarray()

在计算时间方面可能没有太大差异。