Home > Mobile >  How to resolve ZeroDivisionError while trying to update one dataframe column value based on multiple
How to resolve ZeroDivisionError while trying to update one dataframe column value based on multiple

Time:07-16

I have a dataframe like this:

Scores Correct Incorrect
3 3 0
0 0 0

I am trying to update and normalize the 'Scores" column in such a way that

df['Scores'] = df['Scores'] / (df['Correct'] df['Incorrect])

But there may be some columns that can cause ZeroDivisionError as you can see in the second row of the dataframe. So I used this code but it still throws ZeroDivisionError:

df['Scores'] = np.where(((df['Correct'] df['Incorrect])>0), df['Scores'] / (df['Correct'] df['Incorrect]), df['Scores'])

What can I do in this scenario?

CodePudding user response:

You can use Series.div or change >0 to !=0 in your np.where

df['Scores'] = df['Scores'].div(df['Correct'] df['Incorrect'])
# or
df['Scores'] = np.where(((df['Correct'] df['Incorrect'])!=0), df['Scores'] / (df['Correct'] df['Incorrect']), df['Scores'])

CodePudding user response:

This code should also work. I think the problem is with the placement of your code if you are placing it inside a loop or something. Please make sure that is correct.

  • Related