2

Is there a netCDF4 equaivalent of the xarray function to select values from a netCDF file for a lat lon and for a specific time-range:

hndl_nc.sel(time=slice(start_date, end_date)).sel(lon=lon, lat=lat, method='nearest')

I do not want to use cdo or nco

user308827
  • 21,227
  • 87
  • 254
  • 417
  • 1
    why not do it in xarray as you already do?. or use .values at the end to extract the data directly as a np.array? – dreab Apr 03 '17 at 13:06

1 Answers1

2

There will be differences based on your particular dataset, but this function like this should pull values out at specific coordinates and time slice:

def variable_pull(site_lat, site_lon, lat, lon, var, time_slice):
    lat_idx = (np.abs(lat-site_lat)).argmin()
    lon_idx = (np.abs(lon-site_lon)).argmin()
    return var[time_slice, lat_idx, lon_idx]

for a dataset opened with netCDF4 similarly to this:

f = ncdf.Dataset("filepath","r")
lat = f.variables['lat'][:]
lon = f.variables['lon'][:]
var = f.variables['var'][:]
f.close()
site_lat = your coordinates of interest
site_lon = your coordinates of interest
values = variable_pull(site_lat, site_lon, lat, lon, var, time_slice)
Rick Berg
  • 148
  • 2
  • 10