在 Pandas 计算中处理除以零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45540015/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:11:50  来源:igfitidea点击:

Handling division by zero in Pandas calculations

pythonpandasdivide-by-zero

提问by Suminda Sirinath S. Dharmasena

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
  1. 将结果设置为系列之一
  2. 将结果设置为特定值

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

情况 1:将数据设置为特定值

0    0
1    0
2    0

case 2: set the value to a specific series

案例 2:将值设置为特定系列

0    1
1    2
2    3

回答by cs95

You can use df.replaceafter division:

您可以df.replace在除法后使用:

(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))

回答by jezrael

I think you can use Series.replace:

我认为你可以使用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

回答by Clock Slave

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

您还可以使用该np.isinf函数检查无穷大值,然后将它们替换为 0。例如

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. ])