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