How Do I Avoid np.where Calculating Divisions By Zero?

41 views Asked by At
Results = np.where(
    thing_minus_1 == 1,
    0,
    (1 - thing) / (1 - thing_minus_1),
)

Running this code causes a warning:

RuntimeWarning: invalid value encountered in divide

This is because it calculates that divide before the where is applied, so it's still calculating it for the zero-denominator elements. It evaluates (1 - thing) / (1 - thing_minus_1), then passes the result of that as the third argument to np.where().

The question is: What do I replace this code with to avoid this warning without simply turning off the warning?

I tried using a regular if statement to fix the issue, but forgot that where looks at an array of elements. So I’m not certain what to do.

Edit: It seems like this is a good solution (provided with help from the comments):

denominator = np.where((1 - thing_minus_1) == 0, 1, (1 - thing_minus_1))
Results = np.where(
    thing_minus_1 == 1,
    0,
    (1 - thing) / denominator,
)
0

There are 0 answers