Python Forum
np.where and np.max Help
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
np.where and np.max Help
#1
Using nump.where and np.max how can i find the index which value is >=10 and if the next value is <10 then the previous value is the correct index.

For example below the answer would be index 4 from py and therefore index 4 from tv and px

This is what i have tried:

tv = np.array([0.6,   0.7,      1.5,   1.6,    1.7,    1.8,   1.9])

px = np.array([2.4,   2.9,      5.7,   6.6,    7.5,    8.4,   9.3])

py = np.array([9.7,   10.1,   10.5,  10.2,  10.1,  9.9,   9.8])


py_values = np.where(py >= 10)

max_py_values = np.max(py_values)
im stuck on how to write the matching index for tv and px
Reply
#2
I do not understand well the condition you are looking for... and many times understanding well the condition is 90% of the difficulty.
I deduce that you are looking for the first index such that:
- The value itself is greater or equal 10
- The next value is smaller than 10.

So in [8, 10.5, 10.7, 9, 10, 9] The result must be 2 not 1 -because the next value is not smaller than 10- neither 4 -because is not the first index that is valid.
The first thing to notice is that the 2nd condition is not relevant for the last element... and this is the key of the solution:
- The first condition is easy: py >= 10
- The second condition is tricky, you need to look at index 0 to value at 1, at index 1 to value at 2... so you need to shift the match 1 index as py[1:] < 9

And now you need to mix both conditions but notice that the 2nd one has 1 element less, the one that corresponds to the last value in the array. The easiest solution is to cut the 1st check with py[:-1] >= 10 that nicely skips the last index.
As a final note remember that 'and' them in numpy you need logical_and (in this case & can also work, but the differences can sometimes produce subtle bugs)
This produces a boolean array that can be used as a mask to select all the values that meet the condition. If you just want the index you can use the argmax function and the fact that in python is True > False.

All toghether
mask = np.logical_and(py[:-1] >= 10, py[1:] < 10)
# Assume at least 1 match... you can add here some check like np.any(mask)
# All the values that meet the condition
all_valid = py[mask]
# Index of the first one
ind = np.argmax(mask)
# 2 ways to obtain the value of the 1st one that meets
value = py[ind]
value = all_valid[0]
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020