Home > database >  how do I find the index of row in an array that the first column has a specific value and the second
how do I find the index of row in an array that the first column has a specific value and the second

Time:06-26

suppose I have an array a with size (n,2) like this:

a=
6   185.153
6   9.50864
1   9.31425
1   16.4629
6   19.6971
1   2.02113
1   14.0193
5   2.92495
3   56.0731
3   77.6965

now I need to find the index of row that the first column is specific value M (for example 3) and the second corresponding column has max value between other rows with first column equals M. for example in the above array the index will be 8 I used the following code but it doese not work and the output is wrong. do you know what is the problem?

indx_nonremoved=np.where([minimum_merge.max(axis=1) ==3 ])[1]

CodePudding user response:

You need to use list comprehensions and the key parameter of max() built-in function:

a=[[6,   185.153],
[6,   9.50864],
[1 ,  9.31425],
[1  , 16.4629],
[6   ,19.6971],
[1   ,2.02113],
[1   ,14.0193],
[5   ,2.92495],
[3   ,56.0731],
[3   ,77.6965]]

print(a.index(max([i for i in a if i[0]==3], key=lambda x : x[1])))
print(numpy.where(a == max([i for i in a if i[0]==3], key=lambda x : x[1]))) #Use this if a is a numpy.ndarray

Output:

9
  • Related