简体   繁体   English

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

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

I have a netCDF variable with 372 time-steps, I need to slice this variable to read in each individual time-step for subsequent processing. 我有一个372个时间步长的netCDF变量,我需要对该变量进行切片以读取每个单独的时间步长,以便进行后续处理。

I have used glob. 我用过glob。 to read in my 12 netCDF files and then defined the variables. 读取我的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'][:] 

I now need to repeat the code below in a loop for each of the 372 time-steps of the variable 'footprint'. 现在,我需要针对变量“足迹”的372个时间步长中的每个循环重复以下代码。

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

I'm new to Python and have a poor grasp of looping. 我是Python的新手,对循环的掌握很差。 Any help would be appreciated, including better explanation/description of my issue. 任何帮助,包括对我的问题的更好的解释/描述,将不胜感激。

You need to determine both the dimensions and shape of the fp variable in order to access it properly. 您需要确定fp变量的尺寸和形状,以便正确访问它。

I'm making assumptions here about those values. 我在这里对这些值进行假设。

Your code implies 3 dimensions: time,lon,lat. 您的代码包含3个维度:时间,lon,lat。 Again just assuming. 再次只是假设。

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

But the code above gets all the times, all the lons, for 1 latitude. 但是,上面的代码会在所有纬度范围内始终保持1纬度。 Slice 1:2 selects 1 value. 切片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