pandas ZeroDivisionError:浮点除以零(python 3.6)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46347411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ZeroDivisionError: float division by zero (python 3.6)
提问by Mohammad Akhtar
I am using the below code to bypass divide by zero error still getting one, not able to figure out what's actually going wrong here.
我正在使用下面的代码绕过除以零错误仍然得到一个,无法弄清楚这里到底出了什么问题。
df.loc[:,'B to A Ratio'] =np.where(df.loc[:,'A']!=0,df.loc[:,'B']/df.loc[:,'A'],np.nan)
FYI, I am doing this operation on a data frame created from pivot table. Column 'A' & 'B' here are just for Illustration.
仅供参考,我正在对从数据透视表创建的数据框执行此操作。此处的“A”和“B”列仅用于说明。
回答by Psidom
As commented by @Divakar, when you use np.where
, the division is still fully evaluated for all the values in the two series; To avoid dividing by zero, you can convert zeros to nan
before division since any value divided by nan
gives nan
:
正如@Divakar 所评论的那样,当您使用 时np.where
,仍会针对两个系列中的所有值对除法进行全面评估;为避免除以零,您可以将零转换为nan
除法之前,因为任何值除以nan
给出nan
:
df = pd.DataFrame({
"A": [1,2,0,3,4],
"B": [0,2,1,0,1]
})
?
df.B.div(df.A.where(df.A != 0, np.nan))
#0 0.00
#1 1.00
#2 NaN
#3 0.00
#4 0.25
#dtype: float64
Also not sure what your pandas version is, dividing by zero in pandas 0.19 ~ 0.20 gives inf
instead of raising an error
也不确定您的Pandas版本是什么,在Pandas 0.19 ~ 0.20 中除以零给出inf
而不是引发错误
df.B / df.A
#0 0.000000
#1 1.000000
#2 inf
#3 0.000000
#4 0.250000
#dtype: float64