Extract netcdf4 variable slice by dimension name
<p>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 </p>

<p>I know how to do this by position. E.g.</p>

<pre><code>from netCDF4 import Dataset
hndl_nc = Dataset(path_to_nc)

# Access by slice
hndl_nc.variables['name_variable'][:,5,:,:]
</code></pre>

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

<p>You can use <a href="http://xarray.pydata.org/en/stable/indexing.html#indexing-with-labeled-dimensions" rel="nofollow">xarray</a>'s indexing capabilities to access netcdf data by dimension name. </p>

<pre><code>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))
</code></pre>

python netcdf