python-xarraynetcdfcdo-climategribeccodes

Cant select subregion of coordinates in xarray


I am trying to convert a weather file from grib to netcdf and then narrow down the area these files are covering.

dsgrib = xr.open_dataset("infile", engine = "cfgrib")
dsgrib.to_netcdf("outfile.nc)

The conversion itself works. But if I try to decrease the area in the netcdf file i either lose variables or latitudes and longitude values.

ds = xr.open_dataset("outfile.nc")
ds = ds.sel(lon=slice(lonmin, lonmax), lat=slice(latmin, latmax))
ds.to_netcdf("newarea.nc")

but when i try to view the contest of the file with cdo from the command line

cdo sinfon newarea.nc

I get the following error:

    subset.to_netcdf("new.nc")
  File "/home/guest/Desktop/MetOcean/dev3.8/lib/python3.8/site-packages/xarray/core/dataset.py", line 1912, in to_netcdf
    return to_netcdf(  # type: ignore  # mypy cannot resolve the overloads:(
  File "/home/guest/Desktop/MetOcean/dev3.8/lib/python3.8/site-packages/xarray/backends/api.py", line 1232, in to_netcdf
    dump_to_store(
  File "/home/guest/Desktop/MetOcean/dev3.8/lib/python3.8/site-packages/xarray/backends/api.py", line 1279, in dump_to_store
    store.store(variables, attrs, check_encoding, writer, unlimited_dims=unlimited_dims)
  File "/home/guest/Desktop/MetOcean/dev3.8/lib/python3.8/site-packages/xarray/backends/common.py", line 270, in store
    self.set_variables(
  File "/home/guest/Desktop/MetOcean/dev3.8/lib/python3.8/site-packages/xarray/backends/common.py", line 308, in set_variables
    target, source = self.prepare_variable(
  File "/home/guest/Desktop/MetOcean/dev3.8/lib/python3.8/site-packages/xarray/backends/netCDF4_.py", line 488, in prepare_variable
    nc4_var = self.ds.createVariable(
  File "src/netCDF4/_netCDF4.pyx", line 2962, in netCDF4._netCDF4.Dataset.createVariable
  File "src/netCDF4/_netCDF4.pyx", line 4299, in netCDF4._netCDF4.Variable.__init__
  File "src/netCDF4/_netCDF4.pyx", line 2029, in netCDF4._netCDF4._ensure_nc_success
RuntimeError: NetCDF: Invalid argument

I have also tried selecting the area in the initial state before converting the grib file to netcdf file and receive the following error

> Warning (cdf_check_variables): Number of time steps undefined, skipped
> variable u10! Warning (cdf_check_variables): Number of time steps
> undefined, skipped variable v10! Warning (cdfInqContents): No data
> arrays found!

Solution

  • This is not an xarray solution, but you can use cdo package to do this in one line if you like:

    from cdo import Cdo
    cdo=Cdo()
    cdo.sellonlatbox(lonmin,lonmax,latmin,latmax,input="in.grb",output="out.nc",options="-f nc4")
    

    Use nc4 for netcdf4, or just nc for netcdf3 output.