简体   繁体   中英

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.

I have used glob. to read in my 12 netCDF files and then defined the variables.

 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'.

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

I'm new to Python and have a poor grasp of looping. 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.

I'm making assumptions here about those values.

Your code implies 3 dimensions: time,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. Slice 1:2 selects 1 value.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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