我正在尝试在 3d 单元格的规则网格和这些单元格的 1d 索引之间建立对应关系。因此,我想要一种在整数三元组 (i, j, k) 和整数 cellnum 之间来回映射的方法。此映射的速度至关重要。
问题说明:
假设 3d 盒子的每个维度都分为 num_divs 个单元格。然后,通过以下 numpy 索引技巧,从 (i, j, k) 到单元格的唯一字典顺序索引的映射变得闪电般快速:
indexing_array = np.arange(num_divs**3).reshape((num_divs, num_divs, num_divs))
举个例子,假设我们有以下数组存储 Npts 点的 x、y 和 z 单元索引:
Npts = 1e6
xidx = np.random.random_integers(0, num_divs-1, Npts)
yidx = np.random.random_integers(0, num_divs-1, Npts)
zidx = np.random.random_integers(0, num_divs-1, Npts)
存储每个三元组的cellnum的数组可以通过以下方式非常有效地计算:
output_cellnum_array = indexing_array[xidx, yidx, zidx]
output_cellnum_array 是 Npts 点的一维数组。每个值都是一个整数,存储每个 (i, j, k) 三元组的字典顺序。上面的代码在我的笔记本电脑上只需要 40 毫秒,这是我针对以下问题的目标基准:
问题:
如何才能达到相同水平的反向行驶速度?给定一维整数数组 input_cellnum_array,如何以相当的速度计算数组 xidx、yidx、zidx?
极其缓慢的解决方案:
使用以下函数运行 for 循环会返回正确的结果,但对于我的应用程序来说速度太慢了:
def reverse_indexer(single_cellnum, num_divs):
i = single_cellnum/(num_divs*num_divs)
remainder = single_cellnum - (num_divs*num_divs*i)
j = remainder/num_divs
remainder -= j*num_divs
k = remainder % num_divs
return i, j, k
最佳答案
我认为您正在寻找 numpy.unravel_index和 numpy.ravel_multi_index 。 numpy.unravel_index
将一维索引映射到多维索引,而 numpy.ravel_multi_index
将多维索引转换为一维索引:
id_1d = np.arange(9)
# getting the indices of the multi-dimensional array
idx,idy,idz = np.unravel_index(id_1d,(3,3,3))
(idx,idy,idz)
(array([0, 0, 0, 0, 0, 0, 0, 0, 0]),
array([0, 0, 0, 1, 1, 1, 2, 2, 2]),
array([0, 1, 2, 0, 1, 2, 0, 1, 2]))
# getting the 1d indecis
np.ravel_multi_index((idx,idy,idz),(3,3,3))
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
关于python - numpy 中 1d 到 3d 索引对应的有效算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29971803/