在 Pandas 计算中处理除以零 [英] Handling division by zero in Pandas calculations
本文介绍了在 Pandas 计算中处理除以零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据:
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
- 将结果设置为系列之一
- 将结果设置为特定值
但以下给出了意外"的结果:
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
我想到达:
case 1:将数据设置为特定值
0 0
1 0
2 0
情况 2:将值设置为特定系列
0 1
1 2
2 3
推荐答案
分割后可以使用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))
这篇关于在 Pandas 计算中处理除以零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文