I am trying to divide the numbers in two columns, as a percent and catch any ZeroDivisionErrors. I have been trying to figure out the formatting works, and so far nothing has worked.
import pandas as pd
def percent_diff(col1, col2):
"""
This function will avoid any error caused by a divide by 0. The result will be 1,
representing that there is a 100 % difference
"""
try:
x = 1 - (col1 / col2)
x = "{:,.2%}".format(x)
return x
except ZeroDivisionError:
x = 'Error'
return x
data = {'a' : [1, 2, 3, 4, 5, 6, 7, 0, 9, 10],
'b' : [10, 9, 0, 7, 6, 5, 4, 3, 2, 1]}
df = pd.DataFrame(data)
df['c'] = percent_diff(df['a'], df['b'])
df.head(10)
I would like another column with a percent like 25.12%
, or Error
if there is a division error. 100.00% would also work in my instance.