0

I'm using the following code to search for the maximum of pred_flat. Is there a direct way to find the second maximum?

line_max_flat = np.max(pred_flat, axis=1)  ##creates an array with 2500 entries, each containing the max of the row

The variable pred_flat is an array of size (2500,5) and the other questions regarding the second maximum only address arrays with 1 column or lists.

EDIT: An example of the input is:

pred_flat=[[0.1,0.2,0.3,0.5,0.7]
           [0.5.0.4,0.9,0.7,0.3]
           [0.9,0.7,0.8,0.4,0.1]]

and the output should be:

line_max_flat=[0.5,0.7,0.8]
3
  • 1
    Well, the second maximum is the minimum (np.min) since you have 2 value per line... Commented May 13, 2021 at 13:23
  • sorry I meant 5! Typo. I'm gonna correct it immediately! Commented May 13, 2021 at 13:31
  • @Bia Is the title correct? Please create a minimal reproducible example meaning define an input, and expected output for that input. Do it on small arrays, of size 10 or less. Commented May 13, 2021 at 13:40

1 Answer 1

1

We could use the nlargest method of the heapq module that returns a list of the first n largest numbers of an iterable, though its not exactly direct, it is a simple enough code and works

import numpy as np
import heapq

pred_flat = np.array([[1, 2, 3, 4, 5],[2, 4, 6, 8, 10],[5, 6, 7, 8, 9]]) # example used in my code

line_max_flat = []
for i in pred_flat:
    # assuming unique elements, otherwise use set(i) below
    _, sec_max = heapq.nlargest(2, i) # returns a list [max, second_max] - here n=2 
    line_max_flat.append(sec_max)

line_max_flat = np.array(line_max_flat) # make array
print(line_max_flat)

Output:

[4 8 8] # which is the expected result from my example array
Sign up to request clarification or add additional context in comments.

1 Comment

ps. in the above example array, each row is already sorted, but it doesnt need to be. Thats just a coincidence

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.