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