在每个网格单元中查找数组索引?

2 投票
1 回答
3254 浏览
提问于 2025-04-17 22:58

我有一组数据,这些数据在x-y平面上分布,但它们还有其他特征,比如大小。我想把这些数据在x-y平面上划分成网格,然后为每个点获取它所在网格的索引,再计算每个网格单元中大小的平均值或标准差。我想看看在x-y平面上的位置和大小之间是否有关系。传统的方法是写两个循环,创建一个三维矩阵来存储每个单元格中数据的索引。我在想,numpy或python中有没有现成的类可以做到这一点?

我知道可以使用 np.histogram2d,但它只返回每个网格中点的数量,而不是每个点在数组中的索引。还有 matplotlib.mlab.griddata 可以在网格单元之间进行插值,但我不想要插值。我只是想获取每个网格单元中点的索引。

xmin=min(Xpos);xmax=max(Xpos)
ymin=min(Ypos);ymax=max(Ypos)
ngridx = 10
ngridy = 10

xi = np.linspace(np.floor(xmin),np.ceil(xmax),ngridx)
yi = np.linspace(np.floor(ymin),np.ceil(ymax),ngridy)
H, xedges, yedges = np.histogram2d(Ypos, Xpos, bins=(xi, yi), normed=False)

np.histogram2d 得到的输出看起来是这样的:

>>>H
array([[  17.,  114.,  301.,  321.,  308.,  163.,  171.,  298.,  316.],
       [ 223.,  211.,  291.,  323.,  282.,  195.,  263.,  198.,  174.],
       [ 304.,  312.,  322.,  295.,  218.,  295.,  259.,  209.,   80.],
       [ 204.,  260.,  298.,  261.,  296.,  241.,   47.,  133.,  189.],
       [ 270.,  265.,  245.,  265.,  286.,  236.,  108.,  214.,  275.],
       [ 276.,  198.,  275.,  235.,  261.,  267.,  223.,  306.,  282.],
       [ 246.,   60.,   88.,  189.,  259.,  225.,  302.,  306.,  328.],
       [ 292.,  138.,    0.,  141.,  297.,  308.,  314.,  276.,  317.],
       [ 169.,  203.,   67.,  220.,  261.,  306.,  329.,  250.,  277.]])

但我想要的是每个网格单元中的索引。我在寻找最快的方法来实现这一点。我想到了这个主意,但不确定这是否是最好的方法:

for i in range(len(xi)-1):
    for j in range(len(yi)-1):
        bxlow=(Xpos>xi[i]); bxup=(Xpos<=xi[i+1])
        bx=bxlow*bxup
        bylow=(Ypos>yi[j]); byup=(Ypos<=yi[j+1])
        by=bylow*byup
        bprim=bx*by

使用 bprim 来区分网格中的数据。有没有更好的建议呢?

1 个回答

0

你可能是在找numpy.indices这个东西吧?

http://docs.scipy.org/doc/numpy/reference/generated/numpy.indices.html

像这样的代码:

 row, col = np.indices( H.shape )

可以帮你得到你想要的结果。

或者,你可能想要的是x和y的坐标?如果是这样的话,

np.meshgrid(xi,yi)

撰写回答