除以0时如何强制熊猫系列引发异常?

时间:2019-02-12 17:46:30

标签: python pandas

我希望我的Pandas系列在被零除时引发异常。尽管可以在执行除法运算后测试无限或NaN值,但将熊猫本身(或Numpy)引发的异常更为干净。下面的代码说明了该问题。

注意:我故意在下面使用Series.divide()而不是/,因为我需要传递函数引用以在要实现的类中进行除法。

import pandas as pd
import numpy as np
import sys

print('Python version: ' + sys.version)
print('Pandas version: ' + pd.__version__)
print('Numpy version: ' + np.__version__)

a = pd.Series([1, 2, 3])
b = pd.Series([1, 0, 1])

print('Division with no change to numpy error settings:')
print(a.divide(b))

print('Division in np.errstate context manager:')
with np.errstate(divide='raise'):
    print(a.divide(b))

print('Division after calling np.seterr:')
np.seterr(all='raise')
print(a.divide(b))

c = np.array([1, 2, 3])
d = np.array([1, 0, 1])

print('Simple numpy array division raises error.')
c / d

上面运行代码的结果:

Python version: 3.7.1 (default, Nov 16 2018, 06:24:50) 
[GCC 6.3.0 20170516]
Pandas version: 0.24.1
Numpy version: 1.16.1
Division with no change to numpy error settings:
0    1.0
1    inf
2    3.0
dtype: float64
Division in np.errstate context manager:
0    1.0
1    inf
2    3.0
dtype: float64
Division after calling np.seterr:
0    1.0
1    inf
2    3.0
dtype: float64
Simple numpy array division raises error.
Traceback (most recent call last):
  File "/opt/project/tests/tmp.py", line 27, in <module>
    c / d
FloatingPointError: divide by zero encountered in true_divide

手动修复:

result = a.divide(b)
if np.isinf(result.values).any():
    raise ZeroDivisionError('Division by zero!')

0 个答案:

没有答案