python - 在 numpy 中 take 的多维等价物是什么

标签 python numpy

我有这段代码

def build_tree_base(blocks, x, y, z):
   indicies = [
        (x  ,z  ,y  ),
        (x  ,z+1,y  ),
        (x  ,z  ,y+1),
        (x  ,z+1,y+1),
        (x+1,z  ,y  ),
        (x+1,z+1,y  ),
        (x+1,z  ,y+1),
        (x+1,z+1,y+1),
    ]
    children = [blocks[i] for i in indicies]
    return Node(children=children)

其中 blocks 是一个 3 维 numpy 数组。

我想做的是用 numpy.take 之类的东西替换列表理解,但是 take 似乎只处理单维索引。是否有类似 take 的东西可以用于多维索引?

此外,我知道您可以通过转置、切片然后 reshape 来完成此操作,但这很慢,所以我正在寻找更好的选择。

最佳答案

Numpy 索引使这很容易......你应该能够做到这样的事情:

def build_tree_base(blocks, x, y, z):
    idx = [x, x, x, x, x+1, x+1, x+1, x+1]
    idz = [z, z+1, z, z+1, z, z+1, z, z+1]
    idy = [y, y, y+1, y+1, y, y, y+1, y+1]
    children = blocks[idx, idz, idy]
    return Node(children=children)

编辑:我应该指出这个(或任何其他 "fancy" indexing )将返回一个副本,而不是原始数组的 View ...

关于python - 在 numpy 中 take 的多维等价物是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3813344/

相关文章:

Python:系统命令中的unicode

python - PCA、truncated_svd 和 svds 在 numpy 和 sklearn 上的不同结果

python - 如何将 Telegram 聊天机器人中的内联键盘设置为 python-telegram-bot 中的其他功能?

python - 寻找两个pytorch张量的非交集

python - to_dict 的奇怪行为

python - 我想标准化我的图像数据以进行深度学习的预处理

Python 构建多个 arg 参数

python - ZIP 格式重复字符

python - Python 列表中的 Numpy.Array?

python - Numpy gcd 函数