【问题标题】:How to slice and loop through a netCDF variable in Python?如何在 Python 中对 netCDF 变量进行切片和循环?
【发布时间】:2018-07-06 10:29:45
【问题描述】:

我有一个包含 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 新手,对循环的掌握很差。任何帮助将不胜感激,包括更好地解释/描述我的问题。

【问题讨论】:

    标签: python loops variables slice netcdf


    【解决方案1】:

    您需要确定 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]
    

    【讨论】:

    • fp 形状是 (293, 391, 372),即 Lat, Lon, Time。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-11-11
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 2021-10-11
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多