【问题标题】:How to access numpy array with a set of indices stored in another numpy array?如何使用存储在另一个 numpy 数组中的一组索引访问 numpy 数组?
【发布时间】:2017-01-31 06:36:48
【问题描述】:

我有一个 numpy 数组,它存储一组我需要访问另一个 numpy 数组的索引。

我尝试使用for 循环,但它没有按预期工作。

情况是这样的:

>>> a
array([[1, 2],
       [3, 4]])
>>> c
array([[0, 0],
       [0, 1]])
>>> a[c[0]]
array([[1, 2],
       [1, 2]])
>>> a[0,0]         # the result I want
1

上面是我实际代码的简化版本,其中c 数组要大得多,所以我必须使用for 循环来获取每个索引。

【问题讨论】:

标签: python arrays numpy


【解决方案1】:

将其转换为tuple:

>>> a[tuple(c[0])]
1

因为listarray 索引触发advanced indexingtuples(大部分)是基本切片。

【讨论】:

    【解决方案2】:

    a 列为c 的索引,将第一列作为行索引,将第二列作为列索引:

    In [23]: a[c[:,0], c[:,1]]
    Out[23]: array([1, 2])
    

    【讨论】:

      猜你喜欢
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      • 2016-03-09
      • 1970-01-01
      • 2020-06-11
      相关资源
      最近更新 更多