python - 了解 xarray groupby

标签 python python-xarray

我正在尝试计算每个组中的成员数量,类似于pandas.DataFrame.groupby.count。但是,它似乎不起作用。这是一个例子:

In [1]: xr_test = xr.DataArray(np.random.rand(6), coords=[[10,10,11,12,12,12]], dims=['dim0'])
        xr_test
Out[1]: <xarray.DataArray (dim0: 6)>
        array([ 0.92908804,  0.15495709,  0.85304435,  0.24039265,  0.3755476 ,
                0.29261274])
        Coordinates:
          * dim0     (dim0) int32 10 10 11 12 12 12

In [2]: xr_test.groupby('dim0').count()
Out[2]: <xarray.DataArray (dim0: 6)>
        array([1, 1, 1, 1, 1, 1])
        Coordinates:
          * dim0     (dim0) int32 10 10 11 12 12 12

但是,我期望这样的输出:

Out[2]: <xarray.DataArray (dim0: 3)>
        array([2, 1, 3])
        Coordinates:
          * dim0     (dim0) int32 10 11 12

发生什么事了?

换句话说:

In [3]: xr_test.to_series().groupby(level=0).count()
Out[3]: dim0
        10    2
        11    1
        12    3
        dtype: int64

最佳答案

这是一个错误! Xarray 当前做出(在本例中是错误的)假设,即与维度对应的坐标具有所有唯一值。这通常是个好主意,但不应该是必需的。如果您创建另一个坐标,这应该可以正常工作,例如, xr_test = xr.DataArray(np.random.rand(6), coords={'aux': ('x', [10,10,11,12,12,12])}, dims=['x'] ) xr_test.groupby('aux').count()

关于python - 了解 xarray groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38065129/

相关文章:

python - 从 html 页面分析和抓取链接

python - 操作数据框以创建数据透视表

python - xarray : Larger than memory array using map_blocks dumping results into . zarr 商店

python - 替换DataArray中的所有数据

python - 由 Xarray 中的一系列坐标定义的多边形的 3D 掩模

python - 使用 lxml xpath 获取一个元素或引发异常

python - 模板 password_reset_form.html 不会覆盖 django 管理模板

python - 在 Ubuntu 上将 Pyqt 安装到替代 Python 版本

python - 由于比例因子和偏移量,导入 Python 时 NetCDF 数据精度下降

python-3.x - 如何知道切片的 xarray Dataset/DataArray 是否为空?