【问题标题】:access elements from matrix in numpy [duplicate]从numpy中的矩阵访问元素[重复]
【发布时间】:2017-08-30 10:48:46
【问题描述】:

我有一个矩阵 A mXn 和一个大小为 m 的数组 该数组指示必须是 A 的索引的列的索引。 所以,一个例子会

A = [[ 1,2,3],[1,4,6],[2,9,0]]

indices = [0,2,1]

我想要的输出是

C = [1,6,9](矩阵A每一行的对应值)

什么是矢量化的方式来做到这一点。 谢谢

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    使用advanced indexing:

    A = np.array([[ 1,2,3],[1,4,6],[2,9,0]])
    indices = np.array([0,2,1])
    
    # here use an array [1,2,3] to represent the row positions, and combined with indices as
    # column positions, it gives an array at corresponding positions (1, 0), (2, 2), (3, 1)
    A[np.arange(A.shape[0]), indices]
    # array([1, 6, 9])
    

    【讨论】:

      【解决方案2】:
      A = np.array([[ 1,2,3],[1,4,6],[2,9,0]])
      
      indices = [0,2,1]
      m=range(0,A.shape[0])
      for b in zip(m,indices):
          print A[b]
      
      output:
      1
      6
      9
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-12
        • 1970-01-01
        相关资源
        最近更新 更多