python - 如何在 Python 中使用索引列表对 np.array 进行索引

标签 python arrays numpy

假设我有一个 N 维 np.array (或只是一个列表)和一个包含 N 个索引的列表。在不使用循环的情况下对数组进行索引的首选/有效方法是什么?

# 4D array with shape of (2, 3, 4, 5)
arr = np.random.random((2, 3, 4, 5))
index = [0, 2, 1, 3]
result = ??? # Equivalent to arr[0, 2, 1, 3]

此外,仅提供 3D 索引,结果应该是最后一个维度的数组。

index = [0, 2, 1]
result2 = ??? # Equivalent to arr[0, 2, 1]

请注意,我无法仅使用通常的语法进行索引,因为实现必须处理不同形状的数组。

我知道 NumPy 支持按数组索引,但其行为有所不同,因为它从数组中挑选值,而不是按维度索引 ( https://docs.scipy.org/doc/numpy/user/basics.indexing.html )。

最佳答案

the docs :

If one supplies to the index a tuple, the tuple will be interpreted as a list of indices.

<小时/>

因此,将 index 更改为元组:

In [46]: np.allclose(arr[tuple([0,2,1])], arr[0,2,1])
Out[46]: True

In [47]: np.allclose(arr[tuple([0,2,1,3])], arr[0,2,1,3])
Out[47]: True

关于python - 如何在 Python 中使用索引列表对 np.array 进行索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41125022/

相关文章:

python - 抓取不伦不类的标签之间的文本

python - 值错误: Expecting property name enclosed in double quotes in Python

python - 如何使用 Pandas 读取不包含标题的 CSV 文件,仅捕获第一列中的数据并执行删除?

ios - 如何在swift中从字符串数组中拆分字符串

c++ - 如何管理固定数组中的对象?

python - 数组的精确直方图

带有命令行 Blender 参数的 Python 脚本

javascript - 返回包含另一个数组中的阶乘数的数组

python - 使用 arctan/arctan2 绘制 a 从 0 到 2π

python - 评估特定子数组的数组