Indexing one array by another in numpy

前端 未结 4 767
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 05:12

Suppose I have a matrix A with some arbitrary values:

array([[ 2, 4, 5, 3],
       [ 1, 6, 8, 9],
       [ 8, 7, 0, 2]])

A

4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 05:27

    You can use NumPy's advanced indexing -

    A[np.arange(A.shape[0])[:,None],B]
    

    One can also use linear indexing -

    m,n = A.shape
    out = np.take(A,B + n*np.arange(m)[:,None])
    

    Sample run -

    In [40]: A
    Out[40]: 
    array([[2, 4, 5, 3],
           [1, 6, 8, 9],
           [8, 7, 0, 2]])
    
    In [41]: B
    Out[41]: 
    array([[0, 0, 1, 2],
           [0, 3, 2, 1],
           [3, 2, 1, 0]])
    
    In [42]: A[np.arange(A.shape[0])[:,None],B]
    Out[42]: 
    array([[2, 2, 4, 5],
           [1, 9, 8, 6],
           [2, 0, 7, 8]])
    
    In [43]: m,n = A.shape
    
    In [44]: np.take(A,B + n*np.arange(m)[:,None])
    Out[44]: 
    array([[2, 2, 4, 5],
           [1, 9, 8, 6],
           [2, 0, 7, 8]])
    

提交回复
热议问题