Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling division by zero in Pandas calculations

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
like image 904
Suminda Sirinath S. Dharmasena Avatar asked Aug 07 '17 05:08

Suminda Sirinath S. Dharmasena


People also ask

How do I stop dividing by zeros in Python?

try: print(1/0) except ZeroDivisionError: print("You can't divide by zero!") Then Python will print this: You can't divide by zero! If you don't specify an exception type on the except line, it will cheerfully catch all exceptions.

How do you do division in pandas?

In the pandas series constructor, the div() or divide() method is used to perform element-wise floating division operation between the two series objects or between a series and a scalar. The method returns a series with resultant floating division values.

How do you divide two values in pandas?

The simple division (/) operator is the first way to divide two columns. You will split the First Column with the other columns here. This is the simplest method of dividing two columns in Pandas.


2 Answers

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))
like image 192
cs95 Avatar answered Oct 20 '22 17:10

cs95


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
like image 25
jezrael Avatar answered Oct 20 '22 18:10

jezrael