I have np 2d array and want to get indexes of max by row.
For example:
JavaScript
x
4
1
3 2 1 3 1
2
0 4 4 1 2
3
1 0 1 1 2
4
Maximum by row is
[3, 4, 2]
.
Indexes are
[(0,0) (0,3) (1,1) (1,2) (2,4)]
I tried smth like this
buf = np.apply_along_axis(lambda x: zip(np.where(x == np.max(x))), axis=1, arr=B)
or this
buf = np.where(B == np.max(B,axis = 1))
But it doesnt work.
Also I can’t use loops (otherwise I wouldn’t use numpy either)
Advertisement
Answer
After finding max
you need set each max as one row then searching in base array like below:
JavaScript
1
17
17
1
>>> a = np.array([[3 ,2 ,1 ,3 ,1],[0, 4 ,4 ,1 ,2],[1, 0, 1, 1, 2]])
2
3
>>> np.max(a, axis=1)
4
array([3, 4, 2])
5
6
>>> np.max(a, axis=1)[:,None]
7
array([[3],
8
[4],
9
[2]])
10
11
>>> np.argwhere(a==np.max(a,1)[:,None])
12
array([[0, 0],
13
[0, 3],
14
[1, 1],
15
[1, 2],
16
[2, 4]])
17
If you want output like as tuple
in your question you can try this:
JavaScript
1
3
1
>>> list(map(tuple, np.argwhere(a==np.max(a,1)[:,None])))
2
[(0, 0), (0, 3), (1, 1), (1, 2), (2, 4)]
3