1

I do not understand why I still have this error:

"RuntimeWarning: divide by zero encountered in true_divide"

It should be prevented by the np.where that I apply. Note that the divison by zero is correctly handled since I end up with a np.nan and not a -inf:

Of course I can artificially ignore the warnings, but I would like to understand...

import pandas as pd
import numpy as np
series_raw = pd.Series([0, float('nan'), 1,4,6,-1], [0,1,2,3,4,5])
print(series_raw)

# Ignore the divide by zero errors
# np.seterr(divide='ignore', invalid='ignore')

x = series_raw.values

values = np.where(np.logical_or(x == 0, np.isnan(x)), np.nan, 10 /x)

# Re-activate the divide by zero errors
# np.seterr(divide='warn', invalid='warn')

series_modified = pd.Series(values, series_raw.index)
print(series_modified)

Outputs:

0    0.0
1    NaN
2    1.0
3    4.0
4    6.0
5   -1.0

dtype: float64
0          NaN
1          NaN
2    10.000000
3     2.500000
4     1.666667
5   -10.000000
dtype: float64

RuntimeWarning: divide by zero encountered in true_divide

realr
  • 3,652
  • 6
  • 23
  • 34
Antoine Collet
  • 348
  • 2
  • 14
  • That's not how `where` works. In Python the arguments to a function are evaluated before the function is called. The conditional is evaluated, as is `nan`, and `1/x`. All the `where` does is select elements from the arguments based on the conditional. – hpaulj Jan 19 '20 at 04:50
  • The `ufunc` `np.divide` has a `where` parameter that behaves more like how you expect. (use it with an `out` parameter). – hpaulj Jan 19 '20 at 04:55
  • See: https://stackoverflow.com/questions/48696344/numpy-where-and-division-by-zero, and https://stackoverflow.com/questions/58102864/how-to-apply-a-natural-logarithm-to-a-matrix-and-obtain-zero-for-when-the-matrix – hpaulj Jan 19 '20 at 05:06

0 Answers0