【发布时间】:2021-10-18 18:26:25
【问题描述】:
我试图将数字分成两列,以百分比的形式捕获任何 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% 也适用于我的实例。
【问题讨论】:
-
x = list(map("{:,.2%}".format, (1 - (col1 / col2))))?
标签: python function error-handling