如何计算 numpy.histogramdd bins 坐标

How to calculate the numpy.histogramdd bins coordinates

我正在使用 numpy.histogramdd 对 3d 点进行分箱。我的目标是计算有多少箱子包含物品,并且它与特定点的距离小于常数。 numpy.histogramdd returns binedges,即"a list of D arrays describing the bin edges for each dimension",但要找到bins坐标并不简单。有没有比我的以下方法更好(并且循环更少)的方法?

hist_bin_centers_list = [binedges[d][:-1] + (binedges[d][1:] - binedges[d][:-1])/2. for d in range(len(binedges))]
indices3d = itertools.product(*[range(len(binedges[d])-1) for d in range(len(binedges))])
ret_indices = []
for i,j,k in indices3d:
    bin_center = [bin[ind] for bin,ind in zip(hist_bin_centers_list, (i, j, k))]
    if hist[i,j,k]>0 and cdist([pos], [bin_center])[0] < max_dist:
        ret_indices.append((i,j,k))
return len(ret_indices)

感谢@DilithiumMatrix 的提议,这里有一个更好的植入:

bin_centers = list(itertools.product(*hist_bin_centers_list))
dists = cdist([pos], bin_centers)[0].reshape(hist.shape)
hits = len(np.where((hist > 0) & (dists < approx))[0])

只使用 numpy.where 怎么样?

例如结合两个条件:

nonzero = numpy.where( (hist > 0) & (binDist < max_dist) )

计算距离数组 binDist,使得 binDist[i,j,k] 是从 bin i,j,kpos 的距离。