代码之家  ›  专栏  ›  技术社区  ›  CottonDog

如何在使用sort()[复制]将数组元素展平并按降序排序后保留其索引

  •  -1
  • CottonDog  · 技术社区  · 1 年前

    我有一个二维整数数组。我需要找到整个数组中的最大值及其索引。

    目前,我正在将阵列压平,然后使用 sort() 函数以找到最高值。问题是我的数组有倍数(12000000+个元素),所以排序后我不知道如何恢复索引。

    maskingarray = Data.copy()
    flatmask = maskingarray.flatten()
    flatmask.sort()
    

    这段代码允许我访问值最高的元素,但我也需要它在2D数组中的位置。

    有没有更好的方法可以让我保留原始数组的索引?最好只找到最大值,而不必压平。

    (上下文:我需要索引,因为我正在进行孔径光度测量,本质上是寻找一个光度最高的星系,并观察其周围的半径)

    谢谢你的帮助

    1 回复  |  直到 1 年前
        1
  •  0
  •   Bryce Smith    1 年前

    这与前面的问题类似,我认为答案在[这个][1] https://stackoverflow.com/questions/5469286/how-to-get-the-index-of-a-maximum-element-in-a-numpy-array-along-one-axis

    使用Numpy[argmax][1]有一个优雅的解决方案 1.https://numpy.org/doc/stable/reference/generated/numpy.argmax.html

    argmax解决方案:

    >>> import numpy as np
    >>> a = np.array([[1,2,3],[4,3,1]])
    >>> i,j = np.unravel_index(a.argmax(), a.shape)
    >>> [i,j]
    [1,0]
    >>> a[i,j]
    4