For each row, I would like to get the index of the largest two values.
JavaScript
x
6
1
import numpy as np
2
3
x = np.array([[7, 5, 6],
4
[4, 9, 3],
5
[1, 6, 7]])
6
Here’s the result I would like to obtain:
JavaScript
1
4
1
[0, 2]
2
[1, 0]
3
[2, 1]
4
Advertisement
Answer
Use np.argsort
along the second axis and take last two values reversed.
JavaScript
1
12
12
1
import numpy as np
2
3
x = np.array([[7, 5, 6],
4
[4, 9, 3],
5
[1, 6, 7]])
6
7
ind = x.argsort(axis=1)[:,-1:-3:-1]
8
print(ind)
9
[[0 2]
10
[1 0]
11
[2 1]]
12