我希望大熊猫在除以零时引发异常,如:
d = {'col1': [2., 0.], 'col2': [4., 0.]}
df = pd.DataFrame(data=d)
2/df
而不是当前的结果:
0 1.000000
1 inf
Name: col1, dtype: float64
任何建议如何实现?
我知道numpy我可以np.seterr(divide='raise')
但熊猫确实忽略了这一点。
非常感谢
它远非理想,但一个可能的选择是将数据帧的元素解释为Python对象,而不是它通常使用的更优化的numpy
或pandas
dtypes:
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
仔细研究源代码和跟踪显示,在pandas
中你可以找到很多像这样的上下文处理程序:
with np.errstate(all='ignore'):
要么
with numeric.errstate(all='ignore'):
这就是为什么np.seterr
被忽略的原因,并且可能没有简单的方法可以摆脱这种情况。