How to deal with “divide by zero” with pandas dataframes when manipulating columns?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to deal with “divide by zero” with pandas dataframes when manipulating columns in Python. So Here I am Explain to you all the possible Methods here.

How to deal with “divide by zero” with pandas dataframes when manipulating columns?

1. How to deal with “divide by zero” with pandas dataframes when manipulating columns?

It would probably be more useful to use a dataframe that actually has zero in the denominator (see the last row of column two).

2. deal with “divide by zero” with pandas dataframes when manipulating columns

It would probably be more useful to use a dataframe that actually has zero in the denominator (see the last row of column two).

Method 1

It would probably be more useful to use a dataframe that actually has zero in the denominator (see the last row of column two).

one       two     three   four   five
a  0.469112 -0.282863 -1.509059    bar   True
b  0.932424  1.224234  7.823421    bar  False
c -1.135632  1.212112 -0.173215    bar  False
d  0.232424  2.342112  0.982342  unbar   True
e  0.119209 -1.044236 -0.861849    bar   True
f -2.104569  0.000000  1.071804    bar  False

>>> df.one / df.two
a   -1.658442
b    0.761639
c   -0.936904
d    0.099237
e   -0.114159
f        -inf  # <<< Note division by zero
dtype: float64

When one of the values is zero, you should get inf or -inf in the result. One way to convert these values is as follows:

df['result'] = df.one.div(df.two)

df.loc[~np.isfinite(df['result']), 'result'] = np.nan  # Or = 0 per part a) of question.
# or df.loc[np.isinf(df['result']), ...

>>> df
one       two     three   four   five    result
a  0.469112 -0.282863 -1.509059    bar   True -1.658442
b  0.932424  1.224234  7.823421    bar  False  0.761639
c -1.135632  1.212112 -0.173215    bar  False -0.936904
d  0.232424  2.342112  0.982342  unbar   True  0.099237
e  0.119209 -1.044236 -0.861849    bar   True -0.114159
f -2.104569  0.000000  1.071804    bar  False       NaN

Method 2

df['one'].divide(df['two'])

Code:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.rand(5,2), columns=list('ab'))
df.loc[[1,3], 'b'] = 0
print(df)

print(df['a'].divide(df['b']))

Result:

a           b
0   0.517925    0.305973
1   0.900899    0.000000
2   0.414219    0.781512
3   0.516072    0.000000
4   0.841636    0.166157

0    1.692717
1         inf
2    0.530023
3         inf
4    5.065297
dtype: float64

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.