Search code examples
pythonpython-xarraygrib

How to iterate in a grib?


I am trying to iterate over a grib file to get all the data but I don't know how to do it. I am doing it in Python.

I am using this code

import xarray as xr

ds = xr.open_dataset("myFile.grib2", engine="pynio")

for v in ds:
    print(ds[v])

The result i am getting are some outputs like this:

<xarray.DataArray 'PERPW_P0_L1_GLL0' (lat_0: 336, lon_0: 720)>
[241920 values with dtype=float32]
Coordinates:
  * lat_0    (lat_0) float32 90.0 89.5 89.0 88.5 ... -76.0 -76.5 -77.0 -77.5
  * lon_0    (lon_0) float32 0.0 0.5 1.0 1.5 2.0 ... 358.0 358.5 359.0 359.5
Attributes:
    center:                                         US National Weather Servi...
    production_status:                              Operational products
    long_name:                                      Primary wave mean period
    units:                                          s
    grid_type:                                      Latitude/longitude
    parameter_discipline_and_category:              Oceanographic products, W...
    parameter_template_discipline_category_number:  [ 0 10  0 11]
    level_type:                                     Ground or water surface
    level:                                          [1.]
    forecast_time:                                  [219]
    forecast_time_units:                            hours
    initial_time:                                   01/18/2021 (00:00)

I am using this file from NOAA.

As far as I know this are like the columns of a table. How can I get the data, for instance, of all level values?


Solution

  • I usually use pygrib for GRIB file, but xarray also good I think.

    G = pygrib.open('file.grb'):
    for g in G:
        print(g)
    

    Get coords and values like this for example...

    latlons = g.latlons()
    values = g.values
    

    check out all the other data available with keys.. need to pick out valid times and forecast step offset, depending on the data.

    print(g.keys())