Reputation: 1412
I would like to have pandas raise an exception when dividing by zero as in:
d = {'col1': [2., 0.], 'col2': [4., 0.]}
df = pd.DataFrame(data=d)
2/df
Instead of the current result:
0 1.000000
1 inf
Name: col1, dtype: float64
Any suggestions how to achieve that?
I know with numpy I can np.seterr(divide='raise')
but pandas does ignore that.
Many thanks
Upvotes: 6
Views: 510
Reputation: 1286
A closer look into the source code and the trace shows that inside pandas
you can find a lot of context handlers like this:
with np.errstate(all='ignore'):
or
with numeric.errstate(all='ignore'):
This is the reason why np.seterr
is ignored and there is probably no easy way to get rid of this.
Upvotes: 1
Reputation: 14847
It's far from ideal, but one potential option is to interpret the elements of your dataframe as Python objects rather than the more optimized numpy
or pandas
dtypes that it typically uses:
In [37]: d = {'col1': [2., 0.], 'col2': [4., 0.]}
...: df = pd.DataFrame(data=d)
...: 2/df
Out[37]:
col1 col2
0 1.0 0.5
1 inf inf
In [38]: 2 / df.astype('O')
---------------------------------------------------------------------------
ZeroDivisionError: float division by zero
Upvotes: 1