【问题标题】:How to index an np.array with a list of indices in Python如何在 Python 中使用索引列表对 np.array 进行索引
【发布时间】:2016-12-13 15:41:05
【问题描述】:

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

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    the docs:

    如果向索引提供一个元组,该元组将被解释为一个索引列表。


    因此,将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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      • 2017-06-19
      • 2019-03-17
      • 2020-03-29
      • 1970-01-01
      相关资源
      最近更新 更多