Handling division by zero in Pandas calculations

佐手、 提交于 2020-12-25 04:00:18

问题


I have the following data:

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

If there is a division by zero I want to in some cases

  1. set the result to one of the series
  2. set the result to a specific value

But the following give "unexpected" results:

a.div(b, fill_value = 0)
0    inf
1    inf
2    inf

a.div(b).fillna(0)
0    inf
1    inf
2    inf

a.div(b).combine_first(a)
0    inf
1    inf
2    inf

I want to arrive at:

case 1: set the data to a specific value

0    0
1    0
2    0

case 2: set the value to a specific series

0    1
1    2
2    3

回答1:


You can use df.replace after division:

(a / b).replace(np.inf, 0)

0    0.0
1    0.0
2    0.0
dtype: float64

(a / b).replace(np.inf, a)

0    1.0
1    2.0
2    3.0
dtype: float64

Want to handle negative infinity too? You'll need:

(a / b).replace((np.inf, -np.inf), (a, a))



回答2:


I think you can use Series.replace:

print (a.div(b.replace(0, np.nan)).fillna(0))
0    0.0
1    0.0
2    0.0
dtype: float64

print (a.div(b.replace(0, np.nan)).fillna(a))
0    1.0
1    2.0
2    3.0
dtype: float64



回答3:


You can also use the np.isinf function to check for infinite values and then substitue them with 0. Ex-

a = np.asarray(np.arange(5))
b = np.asarray([1,2,0,1,0])

c = a/b
c[np.isinf(c)] = 0

#result
>>> c
array([ 0. ,  0.5,  0. ,  3. ,  0. ])


来源:https://stackoverflow.com/questions/45540015/handling-division-by-zero-in-pandas-calculations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!