如何在Python中从netCDF提取经度和纬度范围内的数据?

时间:2020-09-30 17:56:33

标签: python gdal netcdf

我已经在nc文件中下载了CMIP5气候模式HadGEM2-CC。我知道如何提取给定经度和纬度的数据,现在我想在一定范围的经度和纬度上进行提取,而不是单独提取数据。

对于经度范围和纬度范围分别为0到90和50到80的我该如何做? 下面是我的代码:

tcmodel = Dataset(path + '/treeFrac_Lmon_HadGEM2-CC_rcp85_r2i1p1_203012-205511.nc')
print(tcmodel.variables.keys())

lon = tcmodel.variables['lon']
lat = tcmodel.variables['lat']
time = tcmodel.variables['time']
tc = tcmodel.variables['treeFrac']

print(tcmodel.dimensions.items())

lon_array = lon[:]
lat_array = lat[:]
time_array = time[:]
date = datetime.datetime(1959, 12, 1)
tc_array = tc[:,:,:]
time = []

for i in time_array:
    time.append(date + datetime.timedelta(i))

time = np.array(time, dtype = 'datetime64')

k = [245:257]
i = np.abs(lon_array - 90).argmin() #This I would like to change to a range
j = np.abs(lat_array - 80).argmin() #This I would like to change to a range

tc_time = tc_array[k,j,i]

如何在经度和纬度范围内做到这一点?

1 个答案:

答案 0 :(得分:-1)

如果您使用的是Linux或macOS,则可以使用nctoolkit(https://nctoolkit.readthedocs.io/en/latest/)进行此操作。

import nctoolkit as nc
data = nc.open_data(path + '/treeFrac_Lmon_HadGEM2-CC_rcp85_r2i1p1_203012-205511.nc')
data.crop(lon = [0,90], lat = [50,90])
# if you want to save the file, just do this
data.to_nc("outfile.nc")