繁体   English   中英

如何在Python中对netCDF变量进行切片和循环?

[英]How to slice and loop through a netCDF variable in Python?

我有一个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'][:] 

现在,我需要针对变量“足迹”的372个时间步长中的每个循环重复以下代码。

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

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

您需要确定fp变量的尺寸和形状,以便正确访问它。

我在这里对这些值进行假设。

您的代码包含3个维度:时间,lon,lat。 再次只是假设。

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

但是,上面的代码会在所有纬度范围内始终保持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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM