python - numpy 中 1d 到 3d 索引对应的有效算法

标签 python arrays performance algorithm numpy

我正在尝试在 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_arrayNpts 点的一维数组。每个值都是一个整数,存储每个 (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_indexnumpy.ravel_multi_indexnumpy.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/

相关文章:

python 从 if 语句和 try-except 调用自定义异常

javascript - Gulp sass (libsass) 使用 return 时速度极慢

javascript - 为什么 let 不比 var 慢?

java - 在数组中查找具有特定变量的自定义对象

javascript - 什么是 JavaScript 的跨浏览器支持 1. 7's new features? Specifically array comprehensions and the "let"声明

MySql MyISAM 插入缓慢

python - 如何使用颠覆 Ctypes Python 绑定(bind)?

python - Django 分页对象与 Postgresql QuerySets 有问题

python - Scrapy:多个 "start_urls"产生重复的结果

javascript - 在javascript中重新排序数组