在python中查找具有5列的数组的第二个最大值



我使用以下代码来搜索pred_flat的最大值。有没有找到第二个最大值的直接方法?

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

变量pred_flat是一个大小为(2500,5(的数组,其他问题是关于第二个最大值只有一列或一个列表的地址数组。

编辑:输入的一个例子是:

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]]

输出应该是:

line_max_flat=[0.5,0.7,0.8]

我们可以使用heapq模块的nlargest方法,该方法返回可迭代对象的前n个最大数的列表,尽管它并不完全直接,但它是一个足够简单的代码,可以使用

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)

输出:

[4 8 8] # which is the expected result from my example array

相关内容

最新更新