Search code examples
pythonmultiprocessingpython-xarraygrib

2D XArray cfgrib engine indexing


I'm wanting to extract data from grib2 files within a window of lat/long.

def get_data(temp_filename):
    ds = xr.open_dataset(temp_filename, engine="cfgrib")
    ds = ds[{'latitude': ds.latitude > 1, 'longitude': ds.longitude > -100}]
    radar_values = ds.to_array()
    print(radar_values)

Gives

IndexError: too many indices for array

Solution

  • It turns out that the error is related to doing 2D indexing with xarray.

    d = ds[{'latitude': ds.latitude > 1, 'longitude': ds.longitude > -100}]
    

    should be done with the where() method

    ds=ds.where(ds.latitude > 1)
    ds=ds.where(ds.longitude > -100)
    

    or by extracting the underlying array with numpy and doing appropriate indexing.

    See http://xarray.pydata.org/en/stable/indexing.html