Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

https://pyresample.readthedocs.io/en/latest/

This package seems a bit more speciallized, and does not have as tight of integration with xarray like xESMF and Verde do. If working with satellite or swath data, this is not one to miss! This package integrates with Satpy https://satpy.readthedocs.io/en/stable/ .

(more) Integration with xarray

Prerequisites

Knowing your way around xarray, numpy is beneficial. This is not deisgned to be an introduction to any of those packages. Would do this notebook after doing the xESMF one!

Imports

appdirs   : 1.4.4
dask      : 2026.8.0
matplotlib: 3.11.2
numpy     : 2.5.4
pandas    : 3.0.6
pyresample: 1.35.0
xarray    : 2026.9.0

Loading in one netCDF

Let’s open this file with xarray:

Loading...

Trying to do the same thing with pyresample:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File ~/micromamba/envs/gridding-cookbook-dev/lib/python3.14/site-packages/xarray/backends/file_manager.py:265, in CachingFileManager._acquire_with_cache_info(self, needs_lock)
    264 try:
--> 265     file = self._cache[self._key]
    266 except KeyError:

File ~/micromamba/envs/gridding-cookbook-dev/lib/python3.14/site-packages/xarray/backends/lru_cache.py:56, in LRUCache.__getitem__(self, key)
     55 with self._lock:
---> 56     value = self._cache[key]
     57     self._cache.move_to_end(key)

KeyError: [<class 'netCDF4._netCDF4.Dataset'>, ('/home/runner/work/gridding-cookbook/gridding-cookbook/notebooks/data/onestorm.nc',), 'r', (('clobber', True), ('diskless', False), ('format', 'NETCDF4'), ('persist', False)), '140f6cb1-9b54-4f46-943e-fab264f230a7']

During handling of the above exception, another exception occurred:

FileNotFoundError                         Traceback (most recent call last)
Cell In[6], line 1
----> 1 area_def, cf_info = load_cf_area('data/onestorm.nc', variable='visible', x='x', y='y')

File ~/micromamba/envs/gridding-cookbook-dev/lib/python3.14/site-packages/pyresample/utils/cf.py:444, in load_cf_area(nc_file, variable, y, x)
    441 if (x is not None and y is None) or (x is None and y is not None):
    442     raise ValueError("You must specify both or neither of x= and y=")
--> 444 nc_handle = _open_nc_file(nc_file)
    445 if variable is None:
    446     # if the variable=None, we search through all variables
    447     area_def, cf_info = _load_cf_area_several_variables(nc_handle)

File ~/micromamba/envs/gridding-cookbook-dev/lib/python3.14/site-packages/pyresample/utils/cf.py:478, in _open_nc_file(nc_file)
    475 if isinstance(nc_file, xr.Dataset):
    476     return nc_file
--> 478 return xr.open_dataset(nc_file)

File ~/micromamba/envs/gridding-cookbook-dev/lib/python3.14/site-packages/xarray/backends/api.py:619, in open_dataset(filename_or_obj, engine, chunks, cache, decode_cf, mask_and_scale, decode_times, decode_timedelta, use_cftime, concat_characters, decode_coords, drop_variables, create_default_indexes, inline_array, chunked_array_type, from_array_kwargs, backend_kwargs, **kwargs)
    607 decoders = _resolve_decoders_kwargs(
    608     decode_cf,
    609     open_backend_dataset_parameters=backend.open_dataset_parameters,
   (...)    615     decode_coords=decode_coords,
    616 )
    618 overwrite_encoded_chunks = kwargs.pop("overwrite_encoded_chunks", None)
--> 619 backend_ds = backend.open_dataset(
    620     filename_or_obj,
    621     drop_variables=drop_variables,
    622     **decoders,
    623     **kwargs,
    624 )
    625 ds = _dataset_from_backend_dataset(
    626     backend_ds,
    627     filename_or_obj,
   (...)    638     **kwargs,
    639 )
    640 return ds

File ~/micromamba/envs/gridding-cookbook-dev/lib/python3.14/site-packages/xarray/backends/netCDF4_.py:797, in NetCDF4BackendEntrypoint.open_dataset(self, filename_or_obj, mask_and_scale, decode_times, concat_characters, decode_coords, drop_variables, use_cftime, decode_timedelta, group, mode, format, clobber, diskless, persist, auto_complex, lock, autoclose)
    775 def open_dataset(
    776     self,
    777     filename_or_obj: T_PathFileOrDataStore,
   (...)    794     autoclose=False,
    795 ) -> Dataset:
    796     filename_or_obj = _normalize_path(filename_or_obj)
--> 797     store = NetCDF4DataStore.open(
    798         filename_or_obj,
    799         mode=mode,
    800         format=format,
    801         group=group,
    802         clobber=clobber,
    803         diskless=diskless,
    804         persist=persist,
    805         auto_complex=auto_complex,
    806         lock=lock,
    807         autoclose=autoclose,
    808     )
    810     store_entrypoint = StoreBackendEntrypoint()
    811     with close_on_error(store), store._manager.acquire_context():

File ~/micromamba/envs/gridding-cookbook-dev/lib/python3.14/site-packages/xarray/backends/netCDF4_.py:555, in NetCDF4DataStore.open(cls, filename, mode, format, group, clobber, diskless, persist, auto_complex, lock, lock_maker, autoclose)
    551 else:
    552     manager = CachingFileManager(
    553         netCDF4.Dataset, filename, mode=mode, kwargs=kwargs, lock=lock
    554     )
--> 555 return cls(manager, group=group, mode=mode, lock=lock, autoclose=autoclose)

File ~/micromamba/envs/gridding-cookbook-dev/lib/python3.14/site-packages/xarray/backends/netCDF4_.py:454, in NetCDF4DataStore.__init__(self, manager, group, mode, lock, autoclose)
    452 self._group = group
    453 self._mode = mode
--> 454 with manager.acquire_context():
    455     self.format = self.ds.data_model
    456     self._filename = self.ds.filepath()

File ~/micromamba/envs/gridding-cookbook-dev/lib/python3.14/contextlib.py:141, in _GeneratorContextManager.__enter__(self)
    139 del self.args, self.kwds, self.func
    140 try:
--> 141     return next(self.gen)
    142 except StopIteration:
    143     raise RuntimeError("generator didn't yield") from None

File ~/micromamba/envs/gridding-cookbook-dev/lib/python3.14/site-packages/xarray/backends/file_manager.py:235, in CachingFileManager.acquire_context(self, needs_lock)
    229 """Context manager for acquiring a file.
    230 
    231 The file stays open until the context exits, even if it is evicted
    232 from the cache in the meantime.
    233 """
    234 with self._pinned():
--> 235     file, cached = self._acquire_with_cache_info(needs_lock)
    236     try:
    237         yield file

File ~/micromamba/envs/gridding-cookbook-dev/lib/python3.14/site-packages/xarray/backends/file_manager.py:278, in CachingFileManager._acquire_with_cache_info(self, needs_lock)
    276     kwargs = kwargs.copy()
    277     kwargs["mode"] = self._mode
--> 278 file = self._opener(*self._args, **kwargs)
    279 if self._mode == "w":
    280     # ensure file doesn't get overridden when opened again
    281     self._mode = "a"

File src/netCDF4/_netCDF4.pyx:2522
-> 2522 'Could not get source, probably due dynamically evaluated source code.'

File src/netCDF4/_netCDF4.pyx:2159
-> 2159 'Could not get source, probably due dynamically evaluated source code.'

FileNotFoundError: [Errno 2] No such file or directory: '/home/runner/work/gridding-cookbook/gridding-cookbook/notebooks/data/onestorm.nc'

This is supposed to fail. Will chat about pro’s and con’s in the summary.

Resampling of gridded data using pyresample

Link to this turtorial is here: https://pyresample.readthedocs.io/en/latest/swath.html#pyresample-bilinear

We will be deconstructing it a bit to get into the details, but all of the code is from the above link.

Unlike using xESMF, this does not depend or work with xarray:

target def type <class 'pyresample.geometry.AreaDefinition'>
xarray.core.dataarray.DataArray
/home/runner/micromamba/envs/gridding-cookbook-dev/lib/python3.14/site-packages/pyproj/crs/crs.py:1295: UserWarning: You will likely lose important projection information when converting to a PROJ string from another format. See: https://proj.org/faq.html#what-is-the-best-format-for-describing-coordinate-reference-systems
  proj = self._crs.to_proj4(version=version)
xarray.core.dataarray.DataArray

Can export to xarray

Loading...
Loading...

Summary

Pyresample is a speciallist program, with strong functionality with satpy. Would reccomend if swath/sat image data is part of your normal workflow. For others, the requirement of the data being CF compliant and API is a hurdle.