我正在使用 numpy.histogramdd 对 3d 点进行分箱。我的目标是计算有多少箱子包含元素,并且它与特定点的距离小于常数。 numpy.histogramdd 返回 binedges,它是“描述每个维度的 bin 边缘的 D 数组列表”,但要找到 bin 坐标并不简单。有没有比我的以下方法更好(并且循环更少)的方法?
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,k< 的距离 到 pos。
