从坐标标签计算 xarray dataarray

Calculate xarray dataarray from coordinate labels

我有一个 DataArray,其中包含两个随时间变化的变量(气象数据),y、x 坐标。 x 和 y 坐标位于投影坐标系 (EPSG:3035) 中并对齐,以便每个单元格几乎完全覆盖 1km LAEA reference grid

的标准单元格

我想准备数据用于 Pandas and/or 数据库表中,所以我想添加 LAEA Gridcell Number/Label 可以直接从 x 和 y 计算通过以下(伪)函数

def func(cell):
    return r'1km{}{}'.format(int(cell['y']/1000), int(cell['x']/1000))      # e.g. 1kmN2782E4850

但据我所知,似乎不可能以某种方式将此函数应用于 DataArray 或 DataSet,以便我可以访问这些坐标变量(至少 .apply_ufunc() 是'真的不适合我。

稍后我可以在 Pandas 上计算它,但我的一些数据集包含 60 到 120 个 Mio。 Cells/Rows/datasets 和 pandas(即使使用 Numba)似乎在这个数量上有问题。在 xarray 上,我可以通过 Dask 在 32 个内核上处理它。

我将不胜感激任何关于如何让它工作的建议。

编辑:对我正在处理的数据的更多见解:

这是最大的一个,有 500 个 Mio 单元,但我能够将其下采样到平方公里分辨率,最终得到大约 160 Mio。细胞

Xarray "vci" with monthly Vegetation Condition Indices over some decades

如果数据集足够小,我可以将其导出为 pandas 数据帧并在那里进行计算,但是那很慢而且不是很稳健,因为内核经常崩溃

您可以在 unvectorised way 中使用 apply_ufunc:

def func(x, y):
    return f'1km{int(y/1000)}{int(x/1000)}'  # e.g. 1kmN2782E4850

xr.apply_ufunc(
    func, # first the function
    x.x,  # now arguments in the order expected by 'func'
    x.y
    )

这是应用函数的方式:

import xarray as xr

# ufunc
def func(x, y):
    #print(y)
     return r'1km{}{}'.format(int(y), int(x))

# test data
ds = xr.tutorial.load_dataset("rasm")

xr.apply_ufunc(
    func, 
    ds.x,
    ds.y,
    vectorize=True,
)

请注意,您不必在您的案例中列出 input_core_dims

此外,由于您的函数未向量化,因此您需要设置 vectorized=True:

vectorize : bool, optional If True, then assume func only takes arrays defined over core dimensions as input and vectorize it automatically with :py:func:numpy.vectorize. This option exists for convenience, but is almost always slower than supplying a pre-vectorized function. Using this option requires NumPy version 1.12 or newer.

使用 vectorized 可能不是最高效的选项,因为它本质上只是循环,但如果您将数据分成块并使用 dask,它可能就足够了。

如果没有,您可以考虑使用例如创建矢量化函数肯定会加快速度的 numba。

可以在 xarray tutorial on applying ufuncs

中找到更多信息