假设我有一个 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/