Home > Mobile >  Try and Except in Pandas operations - how to do it?
Try and Except in Pandas operations - how to do it?

Time:07-27

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.

CodePudding user response:

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    
  • Related