Home > Software design >  How to instruct pandas to return 0 if it is trying to divide 0 by 0?
How to instruct pandas to return 0 if it is trying to divide 0 by 0?

Time:05-08

I have the following df

When I execute the following line:

df['var3'] = df['var1']/df['var2']

I get:

ID  date  var1   var2   var3
A   2019Q3  1      2     0.5
A   2019Q4  1      1      1
B   2019Q3  0     NaN    NaN
B   2019Q4  0      0     NaN
...

Is there a way to tell python to return 0 if it is trying to divide 0 by 0? so,

ID  date  var1   var2   var3
A   2019Q3  1      2     0.5
A   2019Q4  1      1      1
B   2019Q3  0     NaN    NaN
B   2019Q4  0      0     *0*
...

CodePudding user response:

A fast solution would be adding this line after the division:

df.loc[(df['var1'] == 0) & (df['var2']== 0), 'var3'] = df[(df['var1'] == 0) & (df['var2']== 0)].fillna(0)

In this way you are selecting rows in which var1 and var2 are equal to 0 and filling the nan with 0.

  • Related