Using Xarray. Isel to Access Data in Grib2 File from a Specific Location?

I'm trying to access the data in a GRIB2 file at a specific longitude and latitude. I have been following along with this tutorial () approximately 2:52 but my GRIB file is formatted differently to the example and uses different variables

import xarray as xr
import pygrib
ds=xr.open_dataset('testdata.grb2', engine='cfgrib', filter_by_keys={'typeOfLevel': 'heightAboveGround', 'topLevel':2})
ds

This prints:

<xarray.Dataset>
Dimensions:            (latitude: 361, longitude: 720)
Coordinates:
    time               datetime64[ns] ...
    step               timedelta64[ns] ...
    heightAboveGround  float64 ...
  * latitude           (latitude) float64 90.0 89.5 89.0 ... -89.0 -89.5 -90.0
  * longitude          (longitude) float64 0.0 0.5 1.0 1.5 ... 358.5 359.0 359.5
    valid_time         datetime64[ns] ...
Data variables:
    t2m                (latitude, longitude) float32 ...
    sh2                (latitude, longitude) float32 ...
    r2                 (latitude, longitude) float32 ...

I then try to use imshow to index along the latitude and longitude (t2m?) dimension using:

t0_ds = ds.isel(t2m={200,200})

which gives this error:

ValueError: Dimensions {'t2m'} do not exist. Expected one or more of Frozen({'latitude': 361, 'longitude': 720})

Obviously there is an error in the way I'm using isel but I have tried many variations and I can't find much information about this particular error

1 Answer

You can access the closest datapoint to a specific latitude/longitude using:

lat = #yourlatitude
lon = #yourlongitude

ds_loc = ds.sel(latitude = lat, longitude = lon, method = 'nearest')

isel is used to access point by index, ie:

ds_loc = ds.isel(latitude = 200)

will return a subset along the 200th latitude value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest