[SOLVED] Return 4 row of np array where the values are the biggest in column 1

Issue

I have the following array MyArray :

[['AZ' 0.144]
 ['RZ' 14.021]
 ['BH' 1003.487]
 ['NE' 1191.514]
 ['FG' 550.991]
 ['MA' nan]]

Where Array dim is :

MyArray.shape
(6,2)

How would I return the 4 Row where values are the biggest ?

So the output would be :

[['RZ' 14.021]
 ['BH' 1003.487]
 ['NE' 1191.514]
 ['FG' 550.991]]

I tried :

MyArray[np.argpartition(MyArray, -2)][:-4]

But this does return an error :

TypeError: '<' not supported between instances of 'float' and 'str'

What am I doing wrong ?

Solution

You just sort by second column and get last 4 rows:

import numpy as np
a = np.array(
    [['AZ', 0.144],
     ['RZ', 14.021],
     ['BH', 1003.487],
     ['NE', 1191.514],
     ['FG', 550.991],
     ['MA', np.nan]],
)

a = a[~np.isnan(a[:, 1].astype(float))]
srt = a[a[:, 1].astype(float).argsort()]
print(srt[-4:, :])

Answered By – MSH

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *