Home > Software design >  How to yield nothing if condition is not fulfilled instead of an alternative using np.where?
How to yield nothing if condition is not fulfilled instead of an alternative using np.where?

Time:12-03

I have a question concerning numpy.where. Beside a condition, the parameters of np.where require both x and y.

  • x: x is yielded where the condition is true.
  • y: y is yielded/used where the condition is not fulfilled.

The part of the related code could look like the following:

BypassZero = np.where(f > 0.00000000000001, f, -8.5)

My question is: is it possible to tell np.where that "nothing" for y instead of -8.5 should be used? An example: if the condition is to use values only higher than 0.00000000000001, as shown above in the code, and this condition is not fulfilled in one numeric value out of a row (of many values), np.where should ignore this step and directly jump to the next numeric value in the row, instead of using -8.5.

CodePudding user response:

Edit: After some suggestions from the comments on my original answer and clarification from the OP, the task is to select those values which satisfy a condition and not include other values.

e.g. If I wanted to select all even numbers and exclude all odd numbers, I'd do it this way:

import numpy as np

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
evens = x[x % 2 == 0]  # select even numbers only
print(evens)

The output:

[ 2  4  6  8 10]

In your case:

result = f[f > 0.00000000000001]

As Timus pointed out, np.where is not necessary at all.

  • Related