【问题标题】:How to find maximum value in whole 2D array with indices [duplicate]如何在具有索引的整个二维数组中找到最大值[重复]
【发布时间】:2019-08-12 12:34:27
【问题描述】:

我想使用 NumPy 查找 2D 数组中的最大值和 Python 中最大值的索引。我用过

np.amax(array)

用于搜索最大值,但我不知道如何获取它的索引。我可以通过使用“for”循环找到它,但也许有更好的方法。

【问题讨论】:

标签: python arrays numpy max


【解决方案1】:

参考这个answer,里面也详细说明了如何求最大值及其(1D)索引,可以使用argmax()

>>> a = array([[10,50,30],[60,20,40]])
>>> maxindex = a.argmax()
>>> maxindex
3

然后您可以使用unravel_index(a.argmax(), a.shape) 将索引作为元组获取:

>>> from numpy import unravel_index
>>> unravel_index(a.argmax(), a.shape)
(1, 0)

【讨论】:

    【解决方案2】:

    在这里,您可以使用返回的索引来测试最大值,当您打印索引时,返回的索引应该类似于(array([0], dtype=int64), array([2], dtype=int64))

    import numpy as np
    a = np.array([[200,300,400],[100,50,300]])
    indices = np.where(a == a.max())
    print(a[indices]) # prints [400]
    
    # Index for max value found two times (two locations)
    a = np.array([[200,400,400],[100,50,300]])
    indices = np.where(a == a.max())
    print(a[indices]) # prints [400 400] because two indices for max
    #Now lets print the location (Index)
    for index in indices:
        print(index)
    

    【讨论】:

      【解决方案3】:

      您可以使用argmax() 来获取您的最大值的索引。

      a = np.array([[10,50,30],[60,20,40]])
      maxindex = a.argmax()
      print maxindex
      

      它应该返回:

      3

      然后你只需要计算这个值来获得行和列的索引。

      最好的

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-05
        • 2021-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多