pythonnetcdf

Extract netcdf4 variable slice by dimension name


I have a netCDF file with 4 dimensions. I want to extract a slice from the netCDF file by giving the name of one of the dimensions

I know how to do this by position. E.g.

from netCDF4 import Dataset
hndl_nc = Dataset(path_to_nc)

# Access by slice
hndl_nc.variables['name_variable'][:,5,:,:]

Given that I know the names of the dimensions, say A, B, C, D. How do I access by dimension name instead of position?


Solution

  • You can use xarray's indexing capabilities to access netcdf data by dimension name.

    import xarray as xr
    ds = xr.open_dataset('./foo.nc')
    var = ds['name_variable']
    # Slice var by Dimension "A" between values 0 and 5
    var_slice = var.sel(A=slice(0,5))