我试图计算每个组中的成员数量,类似于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/

10-12 07:33