I have a two equal sized 2d arrays for which I what to find the maximum value in the first and the corresponding value in the other.
I can get the index for the maximum in the first array by using numpy.argmax(). This gives me an array of indexes for which I want to find the value in the second 2d array corresponding to that index.
import numpy as np
a = np.array([[4,1,5,6],[6,8,1,2],[4,3,5,2],[5,6,2,8]])
b = np.array([[2,6,3,8],[3,5,8,3],[4,6,8,9],[6,2,4,7]])
index_max_a = np.argmax(a, axis=1)
print(index_max_a)
Which gives me:
array([3,1,2,3], dtype=int64)
Then my naive approach was to do:
b[:,index_max_a]
but this does not give the searched for list.
I can get the corresponding value to that index in b one by one as:
b[0,3]
b[1,1]
b[2,2]
b[3,3]
but can I do this in one swoop since I have the indexes in an array? I want to avoid using a for loop, since the arrays I am handling are quite large.
Ultimately a want to get a list which looks like (from this example):
array([8, 5, 8, 7])
It might be some syntax which I am missing. Thank you.
b[np.arange(index_max_a.size), index_max_a]b[np.arange(b.shape[0])[:, None], np.arange(b.shape[1])[None], np.argmax(a, axis=2)]