Issue
list_val = [ 30, 120, 240, 510]
num = 900
np.argmax(np.asarray(list_val) > num)
I want to find the position of first element in array which is greater than num
The output from code above is 0. However, since 900 is greater than 510, the result should be 3. How can I fix it?
--EDIT
I want a solution that works if num is 20, 200 or 900.
Solution
In [248]: x = np.array([ 30, 120, 240, 510])
In [249]: x>200
Out[249]: array([False, False, True, True], dtype=bool)
In [250]: np.argmax(_)
Out[250]: 2
In [251]: x>400
Out[251]: array([False, False, False, True], dtype=bool)
In [252]: np.argmax(_)
Out[252]: 3
In [253]: x>600
Out[253]: array([False, False, False, False], dtype=bool)
In [254]: np.argmax(_)
In [255]: np.max(__)
Out[255]: False
With the large threshhold, the comparison produces all False
. The maximum value is then False
, and the 0th item is that.
You may have to test the x>n
for all False
and return a different value in that case. This is not a universally defined behavior.
Lists have a find
In [261]: (x>200).tolist().index(True)
Out[261]: 2
In [262]: (x>400).tolist().index(True)
Out[262]: 3
In [263]: (x>600).tolist().index(True)
...
ValueError: True is not in list
The string
find
returns a -1
if the value is not found.
In [266]: def foo(test):
...: if not test.any():
...: return -1
...: return np.argmax(test)
...:
In [267]: foo(x>200)
Out[267]: 2
In [268]: foo(x>400)
Out[268]: 3
In [269]: foo(x>600)
Out[269]: -1
Answered By - hpaulj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.