简体   繁体   中英

How to find the nth largest number's index in a 2-dimensions matrix?

I have a matrix like this在此处输入图像描述

I want to find the nth largest number's index in this matrix without breaking it, is there any way to do that?

You could try something as follows:

import numpy as np
import math

def get_largest_index(arr, nth):
    
    # flatten array and get index of sort
    flat_ind_sort = arr.flatten().argsort()
    
    # if nth is out of bounds, return smallest
    if nth > len(flat_ind_sort):
        nth = len(flat_ind_sort)
        print('Warning. Supplied nth is out of bounds. Returning smallest')
    
    # last elem will be index of max val
    idx_nth = flat_ind_sort[-1*nth]
    
    # convert flat index into tuple of coords for orig arr (arr.shape)
    coords = np.unravel_index([idx_nth],arr.shape)

    x, y = coords[0][0], coords[1][0]

    return x, y

arr = np.random.rand(2,3)

# array([[0.20719063, 0.03955628, 0.65236656],
#        [0.82384201, 0.11928533, 0.76487719]])

ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n//10%10!=1)*(n%10<4)*n%10::4])

for i in range(1,math.prod(arr.shape)+1):
    coords = get_largest_index(arr, i)
    print(f'{ordinal(i)} largest at {coords}: {arr[coords]}')

# 1st largest at (1, 0): 0.8238420131656327
# 2nd largest at (1, 2): 0.7648771886978403
# 3rd largest at (0, 2): 0.6523665637022131
# 4th largest at (0, 0): 0.20719063448844777
# 5th largest at (1, 1): 0.11928533253344997
# 6th largest at (0, 1): 0.03955627857150146

# error handling nth is out of bounds

coords = get_largest_index(arr, math.prod(arr.shape)+2)
print(f'{ordinal(i)} largest {coords}: {arr[coords]}')

# Warning. Supplied nth is out of bounds. Returning smallest
# 6th largest (0, 1): 0.03955627857150146

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM