21. Xarray Interpolation, Groupby, Resample, Rolling, and Coarsen#

Attribution: This notebook is a revision of the Xarray Interpolation, Groupby, Resample, Rolling, and Coarsen notebook by Ryan Abernathey from An Introduction to Earth and Environmental Data Science. Thanks to Aiyin Zhang for preparing this notebook.

In this lesson, we cover some more advanced aspects of xarray.

import numpy as np
import xarray as xr
from matplotlib import pyplot as plt

21.1. Interpolation#

In the previous lesson on Xarray, we learned how to select data based on its dimension coordinates and align data with dimension different coordinates. But what if we want to estimate the value of the data variables at different coordinates. This is where interpolation comes in.

# we write it out explicitly so we can see each point.
x_data = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
f = xr.DataArray(x_data**2, dims=['x'], coords={'x': x_data})
f
<xarray.DataArray (x: 11)>
array([  0,   1,   4,   9,  16,  25,  36,  49,  64,  81, 100])
Coordinates:
  * x        (x) int64 0 1 2 3 4 5 6 7 8 9 10
f.plot(marker='o')
[<matplotlib.lines.Line2D at 0x78266cdaeed0>]
../_images/3cf02d6ff1c6161949524b88b90cede34990afb168d313ae65c3d460ebea18f5.png
f.sel(x=3)
<xarray.DataArray ()>
array(9)
Coordinates:
    x        int64 3

We only have data on the integer points in x. But what if we wanted to estimate the value at, say, 4.5?

f.sel(x=4.5)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File /srv/conda/envs/notebook/lib/python3.11/site-packages/pandas/core/indexes/base.py:3652, in Index.get_loc(self, key)
   3651 try:
-> 3652     return self._engine.get_loc(casted_key)
   3653 except KeyError as err:

File /srv/conda/envs/notebook/lib/python3.11/site-packages/pandas/_libs/index.pyx:147, in pandas._libs.index.IndexEngine.get_loc()

File /srv/conda/envs/notebook/lib/python3.11/site-packages/pandas/_libs/index.pyx:155, in pandas._libs.index.IndexEngine.get_loc()

File pandas/_libs/index_class_helper.pxi:70, in pandas._libs.index.Int64Engine._check_type()

KeyError: 4.5

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
File /srv/conda/envs/notebook/lib/python3.11/site-packages/xarray/core/indexes.py:486, in PandasIndex.sel(self, labels, method, tolerance)
    485 try:
--> 486     indexer = self.index.get_loc(label_value)
    487 except KeyError as e:

File /srv/conda/envs/notebook/lib/python3.11/site-packages/pandas/core/indexes/base.py:3654, in Index.get_loc(self, key)
   3653 except KeyError as err:
-> 3654     raise KeyError(key) from err
   3655 except TypeError:
   3656     # If we have a listlike key, _check_indexing_error will raise
   3657     #  InvalidIndexError. Otherwise we fall through and re-raise
   3658     #  the TypeError.

KeyError: 4.5

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
Cell In[5], line 1
----> 1 f.sel(x=4.5)

File /srv/conda/envs/notebook/lib/python3.11/site-packages/xarray/core/dataarray.py:1549, in DataArray.sel(self, indexers, method, tolerance, drop, **indexers_kwargs)
   1439 def sel(
   1440     self: T_DataArray,
   1441     indexers: Mapping[Any, Any] | None = None,
   (...)
   1445     **indexers_kwargs: Any,
   1446 ) -> T_DataArray:
   1447     """Return a new DataArray whose data is given by selecting index
   1448     labels along the specified dimension(s).
   1449 
   (...)
   1547     Dimensions without coordinates: points
   1548     """
-> 1549     ds = self._to_temp_dataset().sel(
   1550         indexers=indexers,
   1551         drop=drop,
   1552         method=method,
   1553         tolerance=tolerance,
   1554         **indexers_kwargs,
   1555     )
   1556     return self._from_temp_dataset(ds)

File /srv/conda/envs/notebook/lib/python3.11/site-packages/xarray/core/dataset.py:2642, in Dataset.sel(self, indexers, method, tolerance, drop, **indexers_kwargs)
   2581 """Returns a new dataset with each array indexed by tick labels
   2582 along the specified dimension(s).
   2583 
   (...)
   2639 DataArray.sel
   2640 """
   2641 indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "sel")
-> 2642 query_results = map_index_queries(
   2643     self, indexers=indexers, method=method, tolerance=tolerance
   2644 )
   2646 if drop:
   2647     no_scalar_variables = {}

File /srv/conda/envs/notebook/lib/python3.11/site-packages/xarray/core/indexing.py:190, in map_index_queries(obj, indexers, method, tolerance, **indexers_kwargs)
    188         results.append(IndexSelResult(labels))
    189     else:
--> 190         results.append(index.sel(labels, **options))
    192 merged = merge_sel_results(results)
    194 # drop dimension coordinates found in dimension indexers
    195 # (also drop multi-index if any)
    196 # (.sel() already ensures alignment)

File /srv/conda/envs/notebook/lib/python3.11/site-packages/xarray/core/indexes.py:488, in PandasIndex.sel(self, labels, method, tolerance)
    486                 indexer = self.index.get_loc(label_value)
    487             except KeyError as e:
--> 488                 raise KeyError(
    489                     f"not all values found in index {coord_name!r}. "
    490                     "Try setting the `method` keyword argument (example: method='nearest')."
    491                 ) from e
    493 elif label_array.dtype.kind == "b":
    494     indexer = label_array

KeyError: "not all values found in index 'x'. Try setting the `method` keyword argument (example: method='nearest')."

Interpolation to the rescue!

f.interp(x=4.5)
<xarray.DataArray ()>
array(20.5)
Coordinates:
    x        float64 4.5

Interpolation uses scipy.interpolate under the hood. There are different modes of interpolation.

# default
f.interp(x=4.5, method='linear').values
array(20.5)
f.interp(x=4.5, method='nearest').values
array(16.)
f.interp(x=4.5, method='cubic').values
array(20.25)

We can interpolate to a whole new coordinate at once:

x_new = x_data + 0.5
f_interp_linear = f.interp(x=x_new, method='linear')
f_interp_cubic = f.interp(x=x_new, method='cubic')
f.plot(marker='o', label='original')
f_interp_linear.plot(marker='o', label='linear')
f_interp_cubic.plot(marker='o', label='cubic')
plt.legend()
<matplotlib.legend.Legend at 0x782661d96250>
../_images/e5de41cfc9d5c12efa8b1139a73ea607d98294d3014348ba6f22de7298e4d661.png

Note that values outside of the original range are not supported:

f_interp_cubic.values
array([ 0.25,  2.25,  6.25, 12.25, 20.25, 30.25, 42.25, 56.25, 72.25,
       90.25,   nan])

Note

You can apply interpolation to any dimension, and even to multiple dimensions at a time. (Multidimensional interpolation only supports mode='nearest' and mode='linear'.) But keep in mind that Xarray has no built-in understanding of geography. If you use interp on lat / lon coordinates, it will just perform naive interpolation of the lat / lon values. More sophisticated treatment of spherical geometry requires another package such as xesmf.

21.2. Groupby#

Xarray copies Pandas’ very useful groupby functionality, enabling the “split / apply / combine” workflow on xarray DataArrays and Datasets. In the first part of the lesson, we will learn to use groupby by analyzing sea-surface temperature data.

First we load a dataset. We will use the NOAA Extended Reconstructed Sea Surface Temperature (ERSST) v5 product, a widely used and trusted gridded compilation of historical data going back to 1854.

Since the data is provided via an OPeNDAP server, we can load it directly without downloading anything:

url = 'http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/noaa.ersst.v5/sst.mnmean.nc'
ds = xr.open_dataset(url, drop_variables=['time_bnds'])
ds = ds.sel(time=slice('1960', '2022'))
ds
<xarray.Dataset>
Dimensions:  (lat: 89, lon: 180, time: 756)
Coordinates:
  * lat      (lat) float32 88.0 86.0 84.0 82.0 80.0 ... -82.0 -84.0 -86.0 -88.0
  * lon      (lon) float32 0.0 2.0 4.0 6.0 8.0 ... 350.0 352.0 354.0 356.0 358.0
  * time     (time) datetime64[ns] 1960-01-01 1960-02-01 ... 2022-12-01
Data variables:
    sst      (time, lat, lon) float32 ...
Attributes: (12/39)
    climatology:                     Climatology is based on 1971-2000 SST, X...
    description:                     In situ data: ICOADS2.5 before 2007 and ...
    keywords_vocabulary:             NASA Global Change Master Directory (GCM...
    keywords:                        Earth Science > Oceans > Ocean Temperatu...
    instrument:                      Conventional thermometers
    source_comment:                  SSTs were observed by conventional therm...
    ...                              ...
    comment:                         SSTs were observed by conventional therm...
    summary:                         ERSST.v5 is developed based on v4 after ...
    dataset_title:                   NOAA Extended Reconstructed SST V5
    _NCProperties:                   version=2,netcdf=4.6.3,hdf5=1.10.5
    data_modified:                   2023-11-03
    DODS_EXTRA.Unlimited_Dimension:  time

Let’s do some basic visualizations of the data, just to make sure it looks reasonable.

ds.sst[0].plot(vmin=-2, vmax=30)
<matplotlib.collections.QuadMesh at 0x782654dd3f50>
../_images/93aeec30954f911338a9a4f7c9b6c531f1b5e6f4b71b4e7f2dc66bb1c5586838.png

Other ways

ds.sst.sel(time = '1960-01-01').plot(vmin=-2, vmax=30)
<matplotlib.collections.QuadMesh at 0x78265439fa90>
../_images/93aeec30954f911338a9a4f7c9b6c531f1b5e6f4b71b4e7f2dc66bb1c5586838.png
ds.sst.isel(time = 0).plot(vmin=-2, vmax=30)
<matplotlib.collections.QuadMesh at 0x78265427b990>
../_images/93aeec30954f911338a9a4f7c9b6c531f1b5e6f4b71b4e7f2dc66bb1c5586838.png

Note that xarray correctly parsed the time index, resulting in a Pandas datetime index on the time dimension.

ds.time
<xarray.DataArray 'time' (time: 756)>
array(['1960-01-01T00:00:00.000000000', '1960-02-01T00:00:00.000000000',
       '1960-03-01T00:00:00.000000000', ..., '2022-10-01T00:00:00.000000000',
       '2022-11-01T00:00:00.000000000', '2022-12-01T00:00:00.000000000'],
      dtype='datetime64[ns]')
Coordinates:
  * time     (time) datetime64[ns] 1960-01-01 1960-02-01 ... 2022-12-01
Attributes:
    long_name:        Time
    delta_t:          0000-01-00 00:00:00
    avg_period:       0000-01-00 00:00:00
    prev_avg_period:  0000-00-07 00:00:00
    standard_name:    time
    axis:             T
    actual_range:     [19723. 81722.]
    _ChunkSizes:      1
ds.sst.sel(lon=300, lat=50).plot()
[<matplotlib.lines.Line2D at 0x78265413b310>]
../_images/7071718cad395a32b4c3554a33de20827d3fa00423de1fe8ff47c65e0e020670.png

As we can see from the plot, the timeseries at any one point is totally dominated by the seasonal cycle. We would like to remove this seasonal cycle (called the “climatology”) in order to better see the long-term variaitions in temperature. We will accomplish this using groupby.

The syntax of Xarray’s groupby is almost identical to Pandas. We will first apply groupby to a single DataArray.

ds.sst.groupby?
Signature:
ds.sst.groupby(
    group: 'Hashable | DataArray | IndexVariable',
    squeeze: 'bool' = True,
    restore_coord_dims: 'bool' = False,
) -> 'DataArrayGroupBy'
Docstring:
Returns a DataArrayGroupBy object for performing grouped operations.

Parameters
----------
group : Hashable, DataArray or IndexVariable
    Array whose unique values should be used to group this array. If a
    Hashable, must be the name of a coordinate contained in this dataarray.
squeeze : bool, default: True
    If "group" is a dimension of any arrays in this dataset, `squeeze`
    controls whether the subarrays have a dimension of length 1 along
    that dimension or if the dimension is squeezed out.
restore_coord_dims : bool, default: False
    If True, also restore the dimension order of multi-dimensional
    coordinates.

Returns
-------
grouped : DataArrayGroupBy
    A `DataArrayGroupBy` object patterned after `pandas.GroupBy` that can be
    iterated over in the form of `(unique_value, grouped_array)` pairs.

Examples
--------
Calculate daily anomalies for daily data:

>>> da = xr.DataArray(
...     np.linspace(0, 1826, num=1827),
...     coords=[pd.date_range("2000-01-01", "2004-12-31", freq="D")],
...     dims="time",
... )
>>> da
<xarray.DataArray (time: 1827)>
array([0.000e+00, 1.000e+00, 2.000e+00, ..., 1.824e+03, 1.825e+03,
       1.826e+03])
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02 ... 2004-12-31
>>> da.groupby("time.dayofyear") - da.groupby("time.dayofyear").mean("time")
<xarray.DataArray (time: 1827)>
array([-730.8, -730.8, -730.8, ...,  730.2,  730.2,  730.5])
Coordinates:
  * time       (time) datetime64[ns] 2000-01-01 2000-01-02 ... 2004-12-31
    dayofyear  (time) int64 1 2 3 4 5 6 7 8 ... 359 360 361 362 363 364 365 366

See Also
--------
:ref:`groupby`
    Users guide explanation of how to group and bin data.
DataArray.groupby_bins
Dataset.groupby
core.groupby.DataArrayGroupBy
pandas.DataFrame.groupby
File:      /srv/conda/envs/notebook/lib/python3.11/site-packages/xarray/core/dataarray.py
Type:      method

21.2.1. Split Step#

The most important argument is group: this defines the unique values we will use to “split” the data for grouped analysis. We can pass either a DataArray or a name of a variable in the dataset. Lets first use a DataArray. Just like with Pandas, we can use the time indexe to extract specific components of dates and times. Xarray uses a special syntax for this .dt, called the DatetimeAccessor.

See a list of datatime properties you can access through .dt here

ds.time.dt
<xarray.core.accessor_dt.DatetimeAccessor at 0x782654284490>
ds.time.dt.month
<xarray.DataArray 'month' (time: 756)>
array([ 1,  2,  3, ..., 10, 11, 12])
Coordinates:
  * time     (time) datetime64[ns] 1960-01-01 1960-02-01 ... 2022-12-01
Attributes:
    long_name:        Time
    delta_t:          0000-01-00 00:00:00
    avg_period:       0000-01-00 00:00:00
    prev_avg_period:  0000-00-07 00:00:00
    standard_name:    time
    axis:             T
    actual_range:     [19723. 81722.]
    _ChunkSizes:      1
ds.time.dt.year
<xarray.DataArray 'year' (time: 756)>
array([1960, 1960, 1960, ..., 2022, 2022, 2022])
Coordinates:
  * time     (time) datetime64[ns] 1960-01-01 1960-02-01 ... 2022-12-01
Attributes:
    long_name:        Time
    delta_t:          0000-01-00 00:00:00
    avg_period:       0000-01-00 00:00:00
    prev_avg_period:  0000-00-07 00:00:00
    standard_name:    time
    axis:             T
    actual_range:     [19723. 81722.]
    _ChunkSizes:      1

We can use these arrays in a groupby operation:

gb = ds.sst.groupby(ds.time.dt.month)
gb
DataArrayGroupBy, grouped over 'month'
12 groups with labels 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12.

Xarray also offers a more concise syntax when the variable you’re grouping on is already present in the dataset. This is identical to the previous line:

gb = ds.sst.groupby('time.month')
gb
DataArrayGroupBy, grouped over 'month'
12 groups with labels 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12.

Now that the data are split, we can manually iterate over the group. The iterator returns the key (group name) and the value (the actual dataset corresponding to that group) for each group.

for group_name, group_da in gb:
    # stop iterating after the first loop
    break

print(group_name)
group_da
1
<xarray.DataArray 'sst' (time: 63, lat: 89, lon: 180)>
[1009260 values with dtype=float32]
Coordinates:
  * lat      (lat) float32 88.0 86.0 84.0 82.0 80.0 ... -82.0 -84.0 -86.0 -88.0
  * lon      (lon) float32 0.0 2.0 4.0 6.0 8.0 ... 350.0 352.0 354.0 356.0 358.0
  * time     (time) datetime64[ns] 1960-01-01 1961-01-01 ... 2022-01-01
Attributes:
    long_name:     Monthly Means of Sea Surface Temperature
    units:         degC
    var_desc:      Sea Surface Temperature
    level_desc:    Surface
    statistic:     Mean
    dataset:       NOAA Extended Reconstructed SST V5
    parent_stat:   Individual Values
    actual_range:  [-1.8     42.32636]
    valid_range:   [-1.8 45. ]
    _ChunkSizes:   [  1  89 180]

21.2.2. Map & Combine#

Now that we have groups defined, it’s time to “apply” a calculation to the group. Like in Pandas, these calculations can either be:

  • aggregation: reduces the size of the group

  • transformation: preserves the group’s full size

At then end of the apply step, xarray will automatically combine the aggregated / transformed groups back into a single object.

Warning

Xarray calls the “apply” step map. This is different from Pandas!

The most fundamental way to apply is with the .map method.

gb.map?
Signature:
gb.map(
    func: 'Callable[..., DataArray]',
    args: 'tuple[Any, ...]' = (),
    shortcut: 'bool | None' = None,
    **kwargs: 'Any',
) -> 'DataArray'
Docstring:
Apply a function to each array in the group and concatenate them
together into a new array.

`func` is called like `func(ar, *args, **kwargs)` for each array `ar`
in this group.

Apply uses heuristics (like `pandas.GroupBy.apply`) to figure out how
to stack together the array. The rule is:

1. If the dimension along which the group coordinate is defined is
   still in the first grouped array after applying `func`, then stack
   over this dimension.
2. Otherwise, stack over the new dimension given by name of this
   grouping (the argument to the `groupby` function).

Parameters
----------
func : callable
    Callable to apply to each array.
shortcut : bool, optional
    Whether or not to shortcut evaluation under the assumptions that:

    (1) The action of `func` does not depend on any of the array
        metadata (attributes or coordinates) but only on the data and
        dimensions.
    (2) The action of `func` creates arrays with homogeneous metadata,
        that is, with the same dimensions and attributes.

    If these conditions are satisfied `shortcut` provides significant
    speedup. This should be the case for many common groupby operations
    (e.g., applying numpy ufuncs).
*args : tuple, optional
    Positional arguments passed to `func`.
**kwargs
    Used to call `func(ar, **kwargs)` for each array `ar`.

Returns
-------
applied : DataArray
    The result of splitting, applying and combining this array.
File:      /srv/conda/envs/notebook/lib/python3.11/site-packages/xarray/core/groupby.py
Type:      method

21.2.2.1. Aggregations#

Like Pandas, xarray’s groupby object has many built-in aggregation operations (e.g. mean, min, max, std, etc):

sst_mm = gb.mean(dim='time')
sst_mm
<xarray.DataArray 'sst' (month: 12, lat: 89, lon: 180)>
array([[[-1.8      , -1.8      , -1.8      , ..., -1.8      ,
         -1.8      , -1.8      ],
        [-1.8      , -1.8      , -1.8      , ..., -1.8      ,
         -1.8      , -1.8      ],
        [-1.8      , -1.8      , -1.8      , ..., -1.8      ,
         -1.8      , -1.8      ],
        ...,
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan],
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan],
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan]],

       [[-1.8      , -1.8      , -1.8      , ..., -1.8      ,
         -1.8      , -1.8      ],
        [-1.8      , -1.8      , -1.8      , ..., -1.8      ,
         -1.8      , -1.8      ],
        [-1.8      , -1.8      , -1.8      , ..., -1.8      ,
         -1.8      , -1.8      ],
...
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan],
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan],
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan]],

       [[-1.7995342, -1.7996206, -1.7998532, ..., -1.7998041,
         -1.7996737, -1.7995361],
        [-1.7995963, -1.799773 , -1.8      , ..., -1.8      ,
         -1.7998328, -1.7996292],
        [-1.8      , -1.8      , -1.8      , ..., -1.8      ,
         -1.8      , -1.8      ],
        ...,
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan],
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan],
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan]]], dtype=float32)
Coordinates:
  * lat      (lat) float32 88.0 86.0 84.0 82.0 80.0 ... -82.0 -84.0 -86.0 -88.0
  * lon      (lon) float32 0.0 2.0 4.0 6.0 8.0 ... 350.0 352.0 354.0 356.0 358.0
  * month    (month) int64 1 2 3 4 5 6 7 8 9 10 11 12
Attributes:
    long_name:     Monthly Means of Sea Surface Temperature
    units:         degC
    var_desc:      Sea Surface Temperature
    level_desc:    Surface
    statistic:     Mean
    dataset:       NOAA Extended Reconstructed SST V5
    parent_stat:   Individual Values
    actual_range:  [-1.8     42.32636]
    valid_range:   [-1.8 45. ]
    _ChunkSizes:   [  1  89 180]

.map accepts as its argument a function. We can pass an existing function:

gb.map(np.mean)
<xarray.DataArray 'sst' (month: 12)>
array([13.67924 , 13.787482, 13.784192, 13.703959, 13.662183, 13.736521,
       13.950218, 14.123172, 14.008661, 13.715476, 13.52839 , 13.548249],
      dtype=float32)
Coordinates:
  * month    (month) int64 1 2 3 4 5 6 7 8 9 10 11 12

Because we specified no extra arguments (like axis) the function was applied over all space and time dimensions. This is not what we wanted. Instead, we could define a custom function. This function takes a single argument–the group dataset–and returns a new dataset to be combined:

def time_mean(a):
    return a.mean(dim='time')

sst_mm = gb.map(time_mean)
sst_mm
<xarray.DataArray 'sst' (month: 12, lat: 89, lon: 180)>
array([[[-1.800001 , -1.800001 , -1.800001 , ..., -1.800001 ,
         -1.800001 , -1.800001 ],
        [-1.800001 , -1.800001 , -1.800001 , ..., -1.800001 ,
         -1.800001 , -1.800001 ],
        [-1.800001 , -1.800001 , -1.800001 , ..., -1.800001 ,
         -1.800001 , -1.800001 ],
        ...,
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan],
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan],
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan]],

       [[-1.800001 , -1.800001 , -1.800001 , ..., -1.800001 ,
         -1.800001 , -1.800001 ],
        [-1.800001 , -1.800001 , -1.800001 , ..., -1.800001 ,
         -1.800001 , -1.800001 ],
        [-1.800001 , -1.800001 , -1.800001 , ..., -1.800001 ,
         -1.800001 , -1.800001 ],
...
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan],
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan],
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan]],

       [[-1.7995352, -1.7996216, -1.7998542, ..., -1.799805 ,
         -1.7996746, -1.7995371],
        [-1.7995974, -1.799774 , -1.800001 , ..., -1.800001 ,
         -1.7998339, -1.7996302],
        [-1.800001 , -1.800001 , -1.800001 , ..., -1.800001 ,
         -1.800001 , -1.800001 ],
        ...,
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan],
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan],
        [       nan,        nan,        nan, ...,        nan,
                nan,        nan]]], dtype=float32)
Coordinates:
  * lat      (lat) float32 88.0 86.0 84.0 82.0 80.0 ... -82.0 -84.0 -86.0 -88.0
  * lon      (lon) float32 0.0 2.0 4.0 6.0 8.0 ... 350.0 352.0 354.0 356.0 358.0
  * month    (month) int64 1 2 3 4 5 6 7 8 9 10 11 12

So we did what we wanted to do: calculate the climatology at every point in the dataset. Let’s look at the data a bit.

Climatlogy at a specific point in the North Atlantic

sst_mm.sel(lon=300, lat=-50).plot()
[<matplotlib.lines.Line2D at 0x78264c002c10>]
../_images/78b7ba481ff5292929b953ca3f0fb6bea534fa4e1d96c6fa709003d0e07743ce.png

Zonal Mean Climatology

sst_mm.mean(dim='lon').transpose().plot.contourf(levels=12, vmin=-2, vmax=30)
<matplotlib.contour.QuadContourSet at 0x78264bee8910>
../_images/1ffd61a73b1acb77e1aa61361a172e10ead4a446f210d9f4b2e5b8f3db5c50cf.png

Difference between January and July Climatology

(sst_mm.sel(month=1) - sst_mm.sel(month=7)).plot(vmax=10)
<matplotlib.collections.QuadMesh at 0x78264bf24690>
../_images/d86e7044e9a1c2bf26746138bd6b174aff9f752427f4f3160e81f175413971d0.png

21.2.2.2. Transformations#

Now we want to remove this climatology from the dataset, to examine the residual, called the anomaly, which is the interesting part from a climate perspective. Removing the seasonal climatology is a perfect example of a transformation: it operates over a group, but doesn’t change the size of the dataset. Here is one way to code it.

def remove_time_mean(x):
    return x - x.mean(dim='time')

ds_anom = ds.groupby('time.month').map(remove_time_mean)
ds_anom
<xarray.Dataset>
Dimensions:  (lat: 89, lon: 180, time: 756)
Coordinates:
  * lat      (lat) float32 88.0 86.0 84.0 82.0 80.0 ... -82.0 -84.0 -86.0 -88.0
  * lon      (lon) float32 0.0 2.0 4.0 6.0 8.0 ... 350.0 352.0 354.0 356.0 358.0
  * time     (time) datetime64[ns] 1960-01-01 1960-02-01 ... 2022-12-01
Data variables:
    sst      (time, lat, lon) float32 1.073e-06 1.073e-06 1.073e-06 ... nan nan

Note

In the above example, we applied groupby to a Dataset instead of a DataArray.

Xarray makes these sorts of transformations easy by supporting groupby arithmetic. This concept is easiest explained with an example:

gb = ds.groupby('time.month')
ds_anom = gb - gb.mean(dim='time')
ds_anom
<xarray.Dataset>
Dimensions:  (lat: 89, lon: 180, time: 756)
Coordinates:
  * lat      (lat) float32 88.0 86.0 84.0 82.0 80.0 ... -82.0 -84.0 -86.0 -88.0
  * lon      (lon) float32 0.0 2.0 4.0 6.0 8.0 ... 350.0 352.0 354.0 356.0 358.0
  * time     (time) datetime64[ns] 1960-01-01 1960-02-01 ... 2022-12-01
    month    (time) int64 1 2 3 4 5 6 7 8 9 10 11 ... 2 3 4 5 6 7 8 9 10 11 12
Data variables:
    sst      (time, lat, lon) float32 0.0 0.0 0.0 0.0 0.0 ... nan nan nan nan

Now we can view the climate signal without the overwhelming influence of the seasonal cycle.

Timeseries at a single point in the North Atlantic

ds_anom.sst.sel(lon=300, lat=50).plot()
[<matplotlib.lines.Line2D at 0x78264be4f090>]
../_images/a1f80f6b823f1f24f9e59fdd65cd82fd6d79978511bfb83424dbd6930c26712d.png

Difference between Jan. 1 2018 and Jan. 1 1960

(ds_anom.sel(time='2022-01-01') - ds_anom.sel(time='1960-01-01')).sst.plot()
<matplotlib.collections.QuadMesh at 0x78264bcc95d0>
../_images/1bce96d21ae7139e320c6086f9cd9e5e288ae5b354de46426ea76b929a8e7a34.png

21.4. Coarsen#

coarsen is a simple way to reduce the size of your data along one or more axes. It is very similar to resample when operating on time dimensions; the key difference is that coarsen only operates on fixed blocks of data, irrespective of the coordinate values, while resample actually looks at the coordinates to figure out, e.g. what month a particular data point is in.

For regularly-spaced monthly data beginning in January, the following should be equivalent to annual resampling. However, results would different for irregularly-spaced data.

ds.coarsen(time=12,boundary = 'exact').mean()
<xarray.Dataset>
Dimensions:  (time: 63, lat: 89, lon: 180)
Coordinates:
  * lat      (lat) float32 88.0 86.0 84.0 82.0 80.0 ... -82.0 -84.0 -86.0 -88.0
  * lon      (lon) float32 0.0 2.0 4.0 6.0 8.0 ... 350.0 352.0 354.0 356.0 358.0
  * time     (time) datetime64[ns] 1960-06-16T08:00:00 ... 2022-06-16T12:00:00
Data variables:
    sst      (time, lat, lon) float32 -1.8 -1.8 -1.8 -1.8 ... nan nan nan nan
Attributes: (12/39)
    climatology:                     Climatology is based on 1971-2000 SST, X...
    description:                     In situ data: ICOADS2.5 before 2007 and ...
    keywords_vocabulary:             NASA Global Change Master Directory (GCM...
    keywords:                        Earth Science > Oceans > Ocean Temperatu...
    instrument:                      Conventional thermometers
    source_comment:                  SSTs were observed by conventional therm...
    ...                              ...
    comment:                         SSTs were observed by conventional therm...
    summary:                         ERSST.v5 is developed based on v4 after ...
    dataset_title:                   NOAA Extended Reconstructed SST V5
    _NCProperties:                   version=2,netcdf=4.6.3,hdf5=1.10.5
    data_modified:                   2023-11-03
    DODS_EXTRA.Unlimited_Dimension:  time

Coarsen also works on spatial coordinates (or any coordiantes).

ds_coarse = ds.coarsen(lon=4, lat=4, boundary='pad').mean()
ds_coarse.sst.isel(time=0).plot(vmin=2, vmax=30, figsize=(12, 5), edgecolor='k')
<matplotlib.collections.QuadMesh at 0x78264b9d15d0>
../_images/1fa4d69cc507bd9d47550a0123d43244dabefb85475cdde4be0055df935cbcc8.png

21.5. An Advanced Example#

In this example we will show a realistic workflow with Xarray. We will

  • Load a “basin mask” dataset

  • Interpolate the basins to our SST dataset coordinates

  • Group the SST by basin

  • Convert to Pandas Dataframe and plot mean SST by basin

basin = xr.open_dataset('http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NODC/.WOA09/.Masks/.basin/dods')
basin
<xarray.Dataset>
Dimensions:  (Y: 180, Z: 33, X: 360)
Coordinates:
  * Y        (Y) float32 -89.5 -88.5 -87.5 -86.5 -85.5 ... 86.5 87.5 88.5 89.5
  * Z        (Z) float32 0.0 10.0 20.0 30.0 50.0 ... 4e+03 4.5e+03 5e+03 5.5e+03
  * X        (X) float32 0.5 1.5 2.5 3.5 4.5 ... 355.5 356.5 357.5 358.5 359.5
Data variables:
    basin    (Z, Y, X) float32 ...
Attributes:
    Conventions:  IRIDL
basin = basin.rename({'X': 'lon', 'Y': 'lat'})
basin
<xarray.Dataset>
Dimensions:  (lat: 180, Z: 33, lon: 360)
Coordinates:
  * lat      (lat) float32 -89.5 -88.5 -87.5 -86.5 -85.5 ... 86.5 87.5 88.5 89.5
  * Z        (Z) float32 0.0 10.0 20.0 30.0 50.0 ... 4e+03 4.5e+03 5e+03 5.5e+03
  * lon      (lon) float32 0.5 1.5 2.5 3.5 4.5 ... 355.5 356.5 357.5 358.5 359.5
Data variables:
    basin    (Z, lat, lon) float32 ...
Attributes:
    Conventions:  IRIDL
basin_surf = basin.basin[0]
basin_surf
<xarray.DataArray 'basin' (lat: 180, lon: 360)>
[64800 values with dtype=float32]
Coordinates:
  * lat      (lat) float32 -89.5 -88.5 -87.5 -86.5 -85.5 ... 86.5 87.5 88.5 89.5
    Z        float32 0.0
  * lon      (lon) float32 0.5 1.5 2.5 3.5 4.5 ... 355.5 356.5 357.5 358.5 359.5
Attributes:
    long_name:  basin code
    units:      ids
    scale_max:  58
    CLIST:      Atlantic Ocean\nPacific Ocean \nIndian Ocean\nMediterranean S...
    valid_min:  1
    valid_max:  58
    scale_min:  1
basin_surf.plot(vmax=10)
#basin_surf
<matplotlib.collections.QuadMesh at 0x78264ba04610>
../_images/dcc509bd7dc55da7e7e58dc5c8ceba276771a1c73cb1b3775b3a2d830f232c69.png
basin_surf_interp = basin_surf.interp_like(ds.sst, method='nearest')
basin_surf_interp.plot(vmax=10)
#basin_surf_interp
<matplotlib.collections.QuadMesh at 0x78264afdfe50>
../_images/3bad6ac95723bda3fa0dd93548232658868fb200cce3eb376a6b55e1f178f0c3.png
ds.sst.groupby(basin_surf_interp).first()
<__array_function__ internals>:200: RuntimeWarning: invalid value encountered in cast
<xarray.DataArray 'sst' (time: 756, basin: 14)>
array([[-1.8       , -1.8       , 23.455315  , ..., -1.8       ,
         3.3971915 , 24.182198  ],
       [-1.8       , -1.8       , 23.722523  , ..., -1.8       ,
         0.03573781, 24.59657   ],
       [-1.8       , -1.8       , 24.601315  , ..., -1.8       ,
        -0.26487017, 26.234186  ],
       ...,
       [ 0.89445347,  4.685296  , 29.049557  , ...,  8.882076  ,
        16.515127  , 29.450462  ],
       [-0.31460398,  1.8985674 , 27.785666  , ...,  3.4794273 ,
        11.925127  , 27.901617  ],
       [-1.8       , -0.24241269, 26.120224  , ...,  1.3552847 ,
         7.9607453 , 25.901285  ]], dtype=float32)
Coordinates:
  * time     (time) datetime64[ns] 1960-01-01 1960-02-01 ... 2022-12-01
  * basin    (basin) float32 1.0 2.0 3.0 4.0 5.0 ... 10.0 11.0 12.0 53.0 56.0
Attributes:
    long_name:     Monthly Means of Sea Surface Temperature
    units:         degC
    var_desc:      Sea Surface Temperature
    level_desc:    Surface
    statistic:     Mean
    dataset:       NOAA Extended Reconstructed SST V5
    parent_stat:   Individual Values
    actual_range:  [-1.8     42.32636]
    valid_range:   [-1.8 45. ]
    _ChunkSizes:   [  1  89 180]
basin_mean_sst = ds.sst.groupby(basin_surf_interp).mean()
basin_mean_sst
<__array_function__ internals>:200: RuntimeWarning: invalid value encountered in cast
<xarray.DataArray 'sst' (time: 756, basin: 14)>
array([[18.585499 , 20.75755  , 21.572077 , ...,  6.238062 ,  6.889794 ,
        26.499819 ],
       [18.705072 , 20.816761 , 21.902283 , ...,  4.8877654,  5.44638  ,
        26.57709  ],
       [18.845848 , 20.865032 , 22.031416 , ...,  4.686406 ,  5.5322194,
        27.90856  ],
       ...,
       [20.133    , 21.700815 , 20.31083  , ..., 17.463427 , 18.683998 ,
        29.5153   ],
       [19.80138  , 21.430943 , 20.964071 , ..., 13.358289 , 14.617571 ,
        28.847633 ],
       [19.636013 , 21.297836 , 21.741606 , ..., 10.26373  , 11.0815325,
        27.899845 ]], dtype=float32)
Coordinates:
  * time     (time) datetime64[ns] 1960-01-01 1960-02-01 ... 2022-12-01
    Z        float32 0.0
  * basin    (basin) float32 1.0 2.0 3.0 4.0 5.0 ... 10.0 11.0 12.0 53.0 56.0
Attributes:
    long_name:     Monthly Means of Sea Surface Temperature
    units:         degC
    var_desc:      Sea Surface Temperature
    level_desc:    Surface
    statistic:     Mean
    dataset:       NOAA Extended Reconstructed SST V5
    parent_stat:   Individual Values
    actual_range:  [-1.8     42.32636]
    valid_range:   [-1.8 45. ]
    _ChunkSizes:   [  1  89 180]
df = basin_mean_sst.mean('time').to_dataframe()
df
Z sst
basin
1.0 0.0 19.317692
2.0 0.0 21.204735
3.0 0.0 21.147755
4.0 0.0 19.902565
5.0 0.0 8.199746
6.0 0.0 15.138650
7.0 0.0 28.522148
8.0 0.0 26.654783
9.0 0.0 0.345633
10.0 0.0 1.550839
11.0 0.0 -0.799598
12.0 0.0 12.162644
53.0 0.0 14.433341
56.0 0.0 28.495367
import pandas as pd
basin_names = basin_surf.attrs['CLIST'].split('\n')
basin_df = pd.Series(basin_names, index=np.arange(1, len(basin_names)+1))
basin_df
1                 Atlantic Ocean
2                 Pacific Ocean 
3                   Indian Ocean
4              Mediterranean Sea
5                     Baltic Sea
6                      Black Sea
7                        Red Sea
8                   Persian Gulf
9                     Hudson Bay
10                Southern Ocean
11                  Arctic Ocean
12                  Sea of Japan
13                      Kara Sea
14                      Sulu Sea
15                    Baffin Bay
16            East Mediterranean
17            West Mediterranean
18                Sea of Okhotsk
19                     Banda Sea
20                 Caribbean Sea
21                 Andaman Basin
22               North Caribbean
23                Gulf of Mexico
24                  Beaufort Sea
25               South China Sea
26                   Barents Sea
27                   Celebes Sea
28                Aleutian Basin
29                    Fiji Basin
30          North American Basin
31           West European Basin
32        Southeast Indian Basin
33                     Coral Sea
34             East Indian Basin
35          Central Indian Basin
36      Southwest Atlantic Basin
37      Southeast Atlantic Basin
38       Southeast Pacific Basin
39               Guatemala Basin
40           East Caroline Basin
41                Marianas Basin
42                Philippine Sea
43                   Arabian Sea
44                   Chile Basin
45                  Somali Basin
46               Mascarene Basin
47                  Crozet Basin
48                  Guinea Basin
49                  Brazil Basin
50               Argentine Basin
51                    Tasman Sea
52         Atlantic Indian Basin
53                   Caspian Sea
54                   Sulu Sea II
55               Venezuela Basin
56                 Bay of Bengal
57                      Java Sea
58    East Indian Atlantic Basin
dtype: object
df = df.join(basin_df.rename('basin_name'))
df.plot.bar(y='sst', x='basin_name')
<Axes: xlabel='basin_name'>
../_images/889252c5ae016840bb9b8ff0ac35ccca054203c09d006feed946ffc250ce6c32.png