有没有办法通过沿时间维度计算每个单元格的模式来聚合 xarrray DataArray?

Is there a way to aggregate an xarrray DataArray by calculating the mode for each cell along the time dimension?

xarray python 包中,可以通过沿某个维度(最常见的是沿时间维度)应用函数来减少 DataArray 的数据。内置函数包括平均值、最小值和最大值等。即:

DataArray.mean(dim = 'time')
DataArray.min(dim = 'time')
DataArray.max(dim = 'time')

据我所知,没有以相同方式计算众数的内置方法。有没有别的办法,例如使用其他包的'help'?

也就是说,一些函数相当于:

DataArray.mode(dim = 'time')

您可以使用 Xarray 的 apply_ufunc 包装 Scipy 的模式函数。有关如何使用 apply_ufunc 的更多示例,请参见 here

def _mode(*args, **kwargs):
    vals = scipy.stats.mode(*args, **kwargs)
    # only return the mode (discard the count)
    return vals[0].squeeze()


def mode(obj, None):
    # note: apply always moves core dimensions to the end
    # usually axis is simply -1 but scipy's mode function doesn't seem to like that
    # this means that this version will only work for DataArray's (not Datasets)
    assert isinstance(obj, xr.DataArray)
    axis = obj.ndim - 1
    return xr.apply_ufunc(_mode, obj,
                          input_core_dims=[[dim]],
                          kwargs={'axis': axis})

使用 xarray 教程数据集的简单示例:

ds = xr.tutorial.load_dataset('air_temperature')

mode(ds, dim='time')

产量:

<xarray.Dataset>
Dimensions:  (lat: 25, lon: 53)
Coordinates:
  * lat      (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
  * lon      (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
Data variables:
    air      (lat, lon) float32 271.5 272.4 272.5 272.1 ... 296.9 296.9 296.79