Dan Schien
Dan Schien

Reputation: 1412

Make pandas raise on divide by zero instead of inf

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

Answers (2)

JoergVanAken
JoergVanAken

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

Randy
Randy

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

Related Questions