Indexing one array by another in numpy

前端 未结 4 1018
佛祖请我去吃肉
佛祖请我去吃肉 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:38

    Following is the solution using for loop:

    outlist = []
    for i in range(len(B)):
        lst = []    
        for j in range(len(B[i])):
            lst.append(A[i][B[i][j]])
        outlist.append(lst)
    outarray = np.asarray(outlist)
    print(outarray)
    

    Above can also be written in more succinct list comprehension form:

    outlist = [ [A[i][B[i][j]] for j in range(len(B[i]))]
                    for i in range(len(B))  ]
    outarray = np.asarray(outlist)
    print(outarray)
    

    Output:

    [[2 2 4 5]
     [1 9 8 6]
     [2 0 7 8]]
    

提交回复
热议问题