groupby_bins 对两个变量?

问题描述 投票:0回答:2

假设我有一个包含 4124 个测量值的数组

nl
。每个都与指定测量发生位置的 (
lat
,
lon
) 对相关联。这些位置没有网格化,即它们没有与规则间隔的值对齐。

In [51]: whos
Variable   Type         Data/Info
---------------------------------
lat        ndarray      4124: 4124 elems, type `float32`, 16496 bytes
lon        ndarray      4124: 4124 elems, type `float32`, 16496 bytes
nl         ndarray      4124: 4124 elems, type `int16`, 8248 bytes

我为

nl
创建一个 DataArray,指定
lat
lon
作为坐标:

nl = xr.DataArray(nl, coords={'lon':(['time'], lon), 'lat':(['time'], lat)}, dims=['time'])

例如,我知道我可以将这些值分组到经度或纬度的容器中以对其进行操作

nl_avg_lon = nl.groupby_bins('lon', np.r_[-180:190:10]).mean()
nl_avg_lat = nl.groupby_bins('lat', np.r_[-90:90:10]).mean()

我想做的是将经度 x 纬度的 2D bin 中的值分组,这样我就可以将结果显示为地图。我认为 groupby_bins 不能做到这一点,还有其他解决方案吗?

更新示例:

这就是我用 numpy 做我想做的事情的方式:

latbins = np.r_[-90:100:10]
lonbins = np.r_[-180:190:10]
nsamples, xx, yy = np.histogram2d(lon, lat, bins=(lonbins, latbins))
nl_sum, xx, yy = np.histogram2d(lon, lat, bins=(lonbins, latbins), weights=nl)
nl_avg = nl_sum / nsamples

我想避免诉诸 numpy 来保持 xarray 与 dash 的集成。

2024年10月25日更新

v2024.09.0 开始,现在 可以在 xarray 中原生实现

python-xarray
2个回答
2
投票

目前正在研究按多维分组,但在 xarray 中尚不可用。

与此同时,有一些非常可以忍受的解决方法。例如,如果您创建第三个坐标,它是

lat
lon
的串联,则可以按该坐标进行分组以生成一组
lat x lon
bins

这是一个简短的例子:

In [12]: da=xr.DataArray(np.random.rand(3,3,2), dims=['lat','lon','time'])

In [13]: da
Out[13]: 
<xarray.DataArray (lat: 3, lon: 3, time: 2)>
array([[[ 0.69092373,  0.94961267],
        [ 0.74086633,  0.22628054],
        [ 0.08215398,  0.16806347]],

       [[ 0.67699002,  0.86242477],
        [ 0.54688503,  0.57882117],
        [ 0.21120849,  0.68743872]],

       [[ 0.43816928,  0.57682212],
        [ 0.10402045,  0.78923986],
        [ 0.53284326,  0.23705761]]])
Coordinates:
  * lat      (lat) int64 0 1 2
  * lon      (lon) int64 0 1 2
  * time     (time) int64 0 1

In [14]: da.stack(latlon=['lat','lon'])
Out[14]: 
<xarray.DataArray (time: 2, latlon: 9)>
array([[ 0.69092373,  0.74086633,  0.08215398,  0.67699002,  0.54688503,
         0.21120849,  0.43816928,  0.10402045,  0.53284326],
       [ 0.94961267,  0.22628054,  0.16806347,  0.86242477,  0.57882117,
         0.68743872,  0.57682212,  0.78923986,  0.23705761]])
Coordinates:
  * time     (time) int64 0 1
  * latlon   (latlon) object (0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) ...

In [15]: da.stack(latlon=['lat','lon']).groupby('latlon').mean()
Out[15]: 
<xarray.DataArray (latlon: 9)>
array([ 0.8202682 ,  0.48357344,  0.12510872,  0.76970739,  0.5628531 ,
        0.44932361,  0.5074957 ,  0.44663016,  0.38495044])
Coordinates:
  * latlon   (latlon) object (0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) ...

0
投票

这里当我将 SABRE 卫星数据分入纬向方式(即纬度和垂直方向)时,您可以给自己带来一些启发。

© www.soinside.com 2019 - 2024. All rights reserved.