我试图将数字分成两列,作为百分比并捕获任何 ZeroDivisionErrors。我一直在试图弄清楚格式化的工作原理,但到目前为止没有任何效果。
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)
我想要另一列带有类似 的百分比25.12%,或者Error如果存在除法错误。100.00% 也适用于我的实例。