Handling division by zero in Pandas calculations

Viewed 12426

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
3 Answers
Related