Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the position of the elements in an array by Python?

I have following array:

scores=[2.619,3.3, 9.67, 0.1, 6.7,3.2]

And I wish to retrieve the elements which more than 5 by following code:

min_score_thresh=5
Result=scores[scores>min_score_thresh]

Hence this will result me result:

[9.67, 6.7]

Now i wish to get the positions of this two element which is my expected answer will be store in variable x:

x = [2,4]

Please share me ideas, thanks

like image 596
user9744314 Avatar asked Dec 11 '22 06:12

user9744314


2 Answers

Use numpy.where for a vectorised solution:

import numpy as np

scores = np.array([2.619,3.3, 9.67, 0.1, 6.7,3.2])
min_score_thresh = 5

res = np.where(scores>min_score_thresh)[0]

print(res)

[2 4]
like image 86
jpp Avatar answered May 12 '23 12:05

jpp


scores = [2.619, 3.3, 9.67, 0.1, 6.7, 3.2]

min_score_thresh = 5

# score is 5 or higher
result = []

# position in 'scores' list
indx = []

for i, item in enumerate(scores):
    if item > min_score_thresh:
        result.append(item)
        indx.append(i)

x = indx

print(result)
print(x)
like image 31
Michael Swartz Avatar answered May 12 '23 14:05

Michael Swartz