Index column values in 2D array using array of ind

2020-04-27 08:15发布

I have the following array:

import numpy as np 

print(A)
array([[ 0,  1,  4,  5,  8,  7],
       [ 5,  3,  4,  1,  8, 11],
       [ 2,  7,  5,  3,  4,  1],
       [ 2,  8,  8,  1, 10,  1],
       [ 2, 14,  8,  6,  5,  3]])

And I need to the values A corresponding to these column indices:

b = np.array([5, 0, 3, 4, 4])

Expected output:

array([ 7,  5,  3, 10,  5])

Thanks in advance.

1条回答
够拽才男人
2楼-- · 2020-04-27 09:12

You can use advanced indexing. You need to define an indexing array across the first axis, so that both indexing arrays are broadcast together and each column index refers to a specific row. In this case you just want an np.arange to index on the rows:

A[np.arange(A.shape[0]), b]
# array([ 7,  5,  3, 10,  5])
查看更多
登录 后发表回答