【问题标题】:find the maximum value and its index in an numpy array在 numpy 数组中找到最大值及其索引
【发布时间】:2015-11-10 21:47:38
【问题描述】:

我有一个类似的数组:

[ [0.0], [0.0020777732133865356], [0.0013433878775686026], [0.00021494206157512963], [8.955918747233227e-05], [0.0], [0.0], [1.7911837858264334e-05], [0.0], [1.7911837858264334e-05], [0.0], [0.0], [0.0], [0.0007702090078964829], [0.02625875361263752], [0.13904960453510284], [0.30124127864837646], [0.30514606833457947], [0.4224506914615631], [0.45712801814079285], [0.5807734131813049], [0.5874545574188232], [0.695248007774353], [0.18126779794692993], [0.11689265072345734], [0.07207723706960678], [0.06512743979692459], [0.06016586348414421], [0.04363323748111725], [0.030235182493925095], [0.03095165640115738], [0.028963441029191017], [0.03578785061836243], [0.029267942532896996]]

我想找到最大值及其索引。 我已经搜索过这个,但没有一个符合我的问题。 有什么解决办法吗? 谢谢。

【问题讨论】:

标签: python opencv


【解决方案1】:

怎么了

In [6]: ind = np.argmax(a)

In [7]: a[ind]
Out[7]: array([ 0.69524801])

由于您有一个二维数组,您可能更喜欢:

In [9]: a[ind][0]
Out[9]: 0.69524800777435303

【讨论】:

    【解决方案2】:

    如果最大值可能不止一个:

    In [16]: arr = np.array([1,4,3,2,5,6,3,5,7,4,7,1,4,7,3])
    In [17]: np.max(arr)
    Out[17]: 7
    In [18]: np.where(arr == np.max(arr))
    Out[18]: (array([ 8, 10, 13]),)
    

    【讨论】:

      【解决方案3】:

      所以,你有一个嵌套列表。下面是步骤。

      创建一个新列表 将所有元素添加到此列表中 对列表进行排序,您将获得最大值并获得索引

      这里是你的数组

      myList = [ ]
      for mylist in a:  
          print mylist[0]
          myList.append(mylist[0])
      

      复制列表

      import copy
      sortedList = copy.copy(myList)
      sortedList.sort()
      sortedList.reverse()
      # to Get the 5 maximum values from the list
      for i in range(0,4):
          print sortedList[i]
          print myList.index(sortedList[i]
      

      【讨论】:

      • 您不需要对整个列表进行排序以获取最大元素。这是 O(nlogn) 复杂度,而不仅仅是 O(n)。另外,我看不到如何使用这种方法获取索引,除非将索引与值一起存储,然后获取该元组的最大值。
      • 我做到了,但错误是:AttributeError: 'numpy.ndarray' object has no attribute 'append'
      • 我还想提取 5 个最大值及其各自的索引。
      • @user5538206 当您说“5 个最大值”时,您是指 5 个最大值,还是恰好是相同最大值的 5 个值?
      • 我的意思是 5 个最高值:)
      猜你喜欢
      • 1970-01-01
      • 2017-09-23
      • 1970-01-01
      • 2022-01-12
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      相关资源
      最近更新 更多