Home > Blockchain >  None of the values greater than a threshold and 2 values greater than a threshold
None of the values greater than a threshold and 2 values greater than a threshold

Time:02-03

I have a numpy array Y with a shape (10,5). I am able to check the values greater than a threshold and their location for each row. But I want to add two things:

  1. If there is a row in which there is no element greater than the threshold then it must print 'None'
  2. If there are multiple elements greater than the threshold then output should be the largest number and it's corresponding location.

Y is as shown below:

[[0.01134 0.09777 0.6773 0.20182 0.01178]

[0.08211 0.35025 0.10659 0.36319 0.09785]

[0.06689 0.50127 0.16266 0.17762 0.09156]

[0.11849 0.43602 0.3991 0.01871 0.02768]

[0.03238 0.68228 0.27775 0.00638 0.0012 ]

[0.79637 0.04201 0.11199 0.0028 0.04684]

[0.57715 0.14894 0.26596 0.00425 0.0037 ]

[0.38991 0.31468 0.2895 0.00269 0.00322]

[0.16056 0.56997 0.25396 0.01414 0.00137]

[0.00005 0.93875 0.04922 0.01175 0.00024]]

The code that I am using is:

 print("Values greater than the threshold:", Y[Y > 0.40])
 print("Their positions:", np.argwhere(Y > 0.40))
 # Threshold here is 0.40

My output so far is:

[[ 0 2]

[ 2 1]

[ 3 1]

[ 4 1]

[ 5 0]

[ 6 0]

[ 8 1]

[ 9 1]]

It can be observed that for rows 1 and 7 since there are no values greater than 0.40, there are no entries in the output. In such scenarios, I want the output as [1 None] and [7 None]

Also, if there is an entry like [0.16056 0.56997 0.45396 0.01414 0.00137] where there are two values greater than 0.40, I want my output to take the largest number (0.56997) and display it's position.

What changes can I make in my code to fulfill all the conditions?

CodePudding user response:

You can use np.any to find rows which have at least one element above the threshold. Then you can use the less-used functionality of np.where which returns values based on whether a condition was met or not.

In [29]: np.where(np.any(y > thr, axis=1), np.argmax(y, axis=1), 'None')
Out[29]:
array(['2', 'None', '1', '1', '1', '0', '0', 'None', '1', '1'],
      dtype='<U21')

Note that the output here has everything as text, and does not match your exact requirement (because I didn't fully understand them), but I think you will be able to modify this to get what you need.

  • Related