Stacey
Stacey

Reputation: 5107

Dividing one dataframe column by another - division by zero

I have a dataframe (dayData), with two columns 'first' and 'average'. I am looking to divide 'first' by 'average' to create a new column 'second'.

Using the following:

dayData["second"] = dayData["first"] / dayData["average"]

However there is the possibility that 'average' can have a value of 0 in thecolumn (so when I divide the two columns I get a 'NaN' value). I would like to replace the 'NaN' value with zero. Is there a quick way to do this?

Thanks

Upvotes: 0

Views: 16861

Answers (2)

user1953366
user1953366

Reputation: 1611

Sometime dataframe datatype is object. In that case also we get divide by zero exception. You can change it to desired datatype. For example if it was int first do:

dayData = dayData.astype(int)

Now divide and it will give NaN and not an exception.

Upvotes: 1

yousraHazem
yousraHazem

Reputation: 423

Your assumption is not entirely correct. You are getting a NaN for dividing zero by zero. If the numerator is a non-zero then you get an Inf. Example:

x = pd.DataFrame(data={'a': [0, 1], 'b':[0, 0]})
x['a'] / x['b']

gives us:

0    NaN
1    inf
dtype: float64

If you just want to remove NaNs then EdChum's answer is the one you need:

dayData["second"] = (dayData["first"] / dayData["average"]).fillna(0)

However if you're getting Inf's then you might need to replace it like so:

dayData["second"].replace([np.inf, -np.inf], 0)

Upvotes: 5

Related Questions