Ask Your Question
2

How can I use Numpy to determine the highest value of an array based on the indices specified in a separate array?

asked 2023-03-17 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-10-31 19:00:00 +0000

bukephalos gravatar image

You can use the function np.argmax() to determine the index of the highest value in an array, and then use this index to extract the corresponding value from another array.

For example, let's say you have an array a and an array of indices idx:

import numpy as np a = np.array([1, 5, 3, 8, 2]) idx = np.array([0, 1, 4]) 

To find the highest value in a based on the indices specified in idx, you can first use np.argmax() to find the index of the highest value in a:

max_idx = np.argmax(a) 

Next, you can check if max_idx is in idx. If it is, then you can simply use a[max_idx] to get the highest value. If not, you can use np.argmax() again, but this time only on a[idx], to find the index of the highest value in a that is also in idx:

if max_idx in idx: max_val = a[max_idx] else: max_idx = np.argmax(a[idx]) max_val = a[idx][max_idx] 

In this example, the highest value in a is 8, which is at index 3. However, since 3 is not in idx, we need to find the highest value in a that is also in idx. In this case, the highest value in a[idx] is 5, which is at index 1. Therefore, max_val is 5.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-17 11:00:00 +0000

Seen: 7 times

Last updated: Oct 31 '22