xarray groupby:对变量应用不同的reducer

时间:2018-03-09 23:07:09

标签: python numpy python-xarray xarray

我使用groupby' categorical_variable +缩减器对空间栅格执行空间叠加/聚合。我想知道是否有办法为某些数据变量使用不同的reducer。例如,在下面的代码中,我希望first()缩小mode(或continuous_variable,但似乎没有实现),mean()import xarray as xr import numpy as np categorical_variable = np.array([[1,1,1,1,1], [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2]], dtype='int16') grouping_variable = np.array([[1,1,1,2,2], [1,1,3,2,2], [1,3,3,3,3], [3,3,3,3,3], [4,4,4,4,4]], dtype='int16') continuous_variable = np.random.rand(5,5) xr_dataset = xr.Dataset({'grouping_variable': xr.DataArray(grouping_variable, dims=['x', 'y']), 'categorical_variable': xr.DataArray(categorical_variable, dims=['x', 'y']), 'continuous_variable': xr.DataArray(continuous_variable, dims=['x', 'y'])}) xr_grouped = xr_dataset.groupby('grouping_variable') xr_reduced = xr_grouped.mean()

缩小
::ApplicationCable::Connection

1 个答案:

答案 0 :(得分:1)

目前在xarray目前的AFAIK中,目前还不能实现这一目标,但是既然你失去了空间结构,你可以很简单地通过熊猫去使用agg

>>> df = xr_dataset.to_dataframe()
>>> df.groupby('grouping_variable').agg({"categorical_variable": "first",
                                         "continuous_variable": "mean"})

                   categorical_variable  continuous_variable
grouping_variable                                           
1                                     1             0.458534
2                                     1             0.822294
3                                     1             0.539483
4                                     1             0.515586