3

So I wrote a code that divides a column by another column:

df['division'] = df['numerator']/df['denominator']

But since the 'denominator' is a result of other calculations, sometimes it is equal to 0. When that is the case, of course we get errors. To prevent that I used try and except like so:

Try:
   df['division'] = df['numerator']/df['denominator']
Except: 
   df['division'] = 0

BUT I think that this doesn't work as I thought it would, since if we get any exceptions ALL the values will be 0 in the division column.

I solved it with:

np.where(df['denominator'] !=0, do_the_thing, 0)

But I wonder if 0 was not the only cause of an exception, what would I do? Is there an efficient way to check exceptions in line by line operations?

Thanks in advance.

Suetam016
  • 101
  • 7
  • But a `denominator` value of `0` doesn't raise an exception in `df['division'] = df['numerator'] / df['denominator']`: The respective result is `inf` if the corresponding `numerator` value is not `0`, otherwise `NaN`? – Timus Jul 27 '22 at 19:16
  • I guess it was then.. but I was getting the ZeroDivisionError exception and a float related one. – Suetam016 Aug 02 '22 at 12:37

1 Answers1

2

if you still want to use try and except and make it specifically for your zero division you can try this :

try:
    df['division'] = df['numerator']/df['denominator']
except ZeroDivisionError:
    df['division'] = 0

This way, you can except only that type of error and live the others raise errors

Something like this ? Please adjust it to your liking as we don't have the df

for index, row in df.iterrows():
    try:
        row['division'] = row['numerator']/row['denominator']
    except ZeroDivisionError:
        row['division'] = 0    
minattosama
  • 263
  • 1
  • 9