如何解决numpy:在ndarray的每一行中查找第二高的值的索引 输出:
我有一个[10,10]
numpy.ndarray
。我正在尝试使索引在每一行中排第二高。因此对于数组:
[101 0 1 0 0 0 1 1 2 0]
[ 0 116 1 0 0 0 0 0 1 0]
[ 1 4 84 2 2 0 2 4 6 1]
[ 0 2 0 84 0 6 0 2 3 0]
[ 0 0 1 0 78 0 0 2 0 11]
[ 2 0 0 1 1 77 5 0 2 0]
[ 1 2 1 0 1 2 94 0 1 0]
[ 0 1 1 0 0 0 0 96 0 4]
[ 1 5 4 3 1 3 0 1 72 4]
[ 0 1 0 0 3 2 0 7 0 82]
预期结果:[8,2,8,5,9,...]
有什么建议吗?
解决方法
神奇的numpy.argsort()
函数使此任务非常简单。找到排序后的索引后,倒数第二列。
m = np.array([[101,1,2,0],[ 0,116,[ 1,4,84,6,1],3,78,11],[ 2,77,5,94,96,4],72,7,82]])
# Get index for the second highest value.
m.argsort()[:,-2]
输出:
array([8,8,9,7],dtype=int32)
,
我对某些事情感到困惑,例如:
1-如果重复最高的数字,您会认为它是第二高的数字吗?
2-如果第二高的数字重复出现,您想知道它在数组中的所有位置还是仅是第一个出现?
无论如何,有我的解释解决方案:
import numpy as np
my_array = np.array([[101,[ 0,[ 1,[ 2,82]])
result = []
for row in my_array:
second = np.sort(row)[-2] #Finds the second highest number
i = np.where(row == second) #Looks for where the condition is true
result.append(i[0][0]) #Appends the first occurence
,
使用argpartition
可能比argsort
In [167]: n = 2
In [168]: arr.argpartition(-n)[:,-n]
Out[168]: array([8,dtype=int32)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。