首页 > 解决方案 > 如何在 Python 中对 netCDF 变量进行切片和循环?

问题描述

我有一个具有 372 个时间步长的 netCDF 变量,我需要对该变量进行切片以读取每个单独的时间步长以进行后续处理。

我用过glob。读入我的 12 个 netCDF 文件,然后定义变量。

NAME_files = glob.glob('RGL*nc')
NAME_files = NAME_files[0:12]

for n in (NAME_files):    
    RGL = Dataset(n, mode='r')
    footprint = RGL.variables['fp'][:]
    lons = RGL.variables['lon'][:]
    lats = RGL.variables['lat'][:]

我现在需要为变量“footprint”的 372 个时间步长中的每一个循环重复下面的代码。

footprint_2 =  RGL.variables['fp'][:,:,1:2]

我是 Python 新手,对循环的掌握很差。任何帮助将不胜感激,包括更好地解释/描述我的问题。

标签: pythonloopsvariablesslicenetcdf

解决方案


您需要确定 fp 变量的尺寸和形状才能正确访问它。

我在这里对这些值做出假设。

您的代码暗示 3 个维度:时间、经度、纬度。再次只是假设。

footprint_2 =  RGL.variables['fp'][:,:,1:2]

但是上面的代码总是得到所有的时间,所有的 lons,1 个纬度。切片 1:2 选择 1 个值。

fp_dims = RGL.variables['fp'].dimensions
print(fp_dims)
# a tuple of dimesions names
 (u'time', u'lon', u'lat')

fp_shape = RGL.variables['fp'].shape

# a tuple of dimesions sizes or lengths
print(fp_shape)
 (372, 30, 30)

len = fp_shape[0]

for time_idx in range(0,len)):
  # you don't say if you want a single lon,lat or all the lon,lat's for a given time step.
  test = RGL.variables['fp'][time_idx,:,:]
  # or if you really want this:
  test = RGL.variables['fp'][time_idx,:,1:2]
  # or a single lon, lat
  test = RGL.variables['fp'][time_idx,8,8]

推荐阅读