【问题标题】:Use 2d array as list of indices for n-D array使用二维数组作为 n 维数组的索引列表
【发布时间】:2016-06-22 18:26:17
【问题描述】:

如果我有以下数据:

A = np.random.random((3, 4, 5))

# np.all(indices < A.shape) is true
indices = np.array([
    [0, 0, 0],
    [1, 2, 4],
    ...
    [2, 3, 4]
])

如何使用indices 的每一行作为 A 中的一组轴索引来给出以下内容?

B = np.array([
    A[0, 0, 0],
    A[1, 2, 4],
    ...
    A[2, 3, 4]
])

【问题讨论】:

    标签: arrays numpy multidimensional-array indexing


    【解决方案1】:

    您可以使用np.ravel_multi_index 生成线性索引,然后使用linear-indexingA 中提取选择性元素,就像这样使用np.take -

    np.take(A,np.ravel_multi_index(indices.T,A.shape))
    

    【讨论】:

      【解决方案2】:

      这是一个二维示例:

      In [1]: A=np.arange(10,22).reshape(3,4)
      In [2]: A
      Out[2]: 
      array([[10, 11, 12, 13],
             [14, 15, 16, 17],
             [18, 19, 20, 21]])
      In [3]: ind=np.array([[0,1],[1,3],[2,0],[0,2]])
      In [4]: ind
      Out[4]: 
      array([[0, 1],
             [1, 3],
             [2, 0],
             [0, 2]])
      In [5]: A[ind[:,0],ind[:,1]]
      Out[5]: array([11, 17, 18, 12])
      

      或者对于你的变量,

      A[indices[:,0], indices[:,1], indices[:,2]]
      

      或更笼统地说:

      In [8]: tuple(ind.T)
      Out[8]: (array([0, 1, 2, 0]), array([1, 3, 0, 2]))
      In [9]: A[tuple(ind.T)]
      Out[9]: array([11, 17, 18, 12])
      

      这是基于A[a,b]A[(a,b)] 相同的想法。而当ab是匹配列表或数组时,通过配对来选择值,大致与

      [A[i,j] for i,j in zip(a,b)]
      

      对于product 之类的索引,索引数组需要有更多维度。 ix_ 是生成此类数组的便捷方式:

      In [53]: np.ix_(ind[:,0],ind[:,1])
      Out[53]: 
      (array([[0],
              [1],
              [2],
              [0]]), array([[1, 3, 0, 2]]))
      In [54]: A[np.ix_(ind[:,0],ind[:,1])]
      Out[54]: 
      array([[11, 13, 10, 12],
             [15, 17, 14, 16],
             [19, 21, 18, 20],
             [11, 13, 10, 12]])
      
      In [56]: A[ind[:,[0]],ind[:,1]]
      Out[56]: 
      array([[11, 13, 10, 12],
             [15, 17, 14, 16],
             [19, 21, 18, 20],
             [11, 13, 10, 12]])
      

      【讨论】:

      • 我的印象是,将多个列表传递给索引表达式更像是 itertools.product 而不是 zip
      • 索引之类的产品是用更高维度的索引来执行的。我会添加一个插图。
      猜你喜欢
      • 1970-01-01
      • 2020-06-11
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      相关资源
      最近更新 更多