我试图将数字分成两列,作为百分比并捕获任何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%对我来说也可以。
直接使用zip:
[a / b for (a, b) in zip(la, lb)]
你可以用一个函数调用(percent_diff
)来代替a / b
来处理你的零除法,就像你做的那样,但不需要管理列表迭代。
也就是说,zip
将把两个列表压缩成一个元组,您可以使用:
>>> la = [1,2,3]
>>> lb = [2,2,2]
>>> [i for i in zip(la, lb)]
[(1, 2), (2, 2), (3, 2)]
>>> [a / b for (a, b) in zip(la, lb)]
[0.5, 1.0, 1.5]
完整的解决方案如下:
def perc(a, b):
try:
result = 1 - (a / b) # Note this inverts the percentage.
return "{:,.2%}".format(result)
except ZeroDivisionError:
return "Error"
data = {'a' : [1, 2, 3, 4, 5, 6, 7, 0, 9, 10],
'b' : [10, 9, 0, 7, 6, 5, 4, 3, 2, 1]}
data["c"] = [perc(a, b) for (a, b) in zip(data.get("a", []), data.get("b", []))]
生成结果:
>>> pprint(data)
{'a': [1, 2, 3, 4, 5, 6, 7, 0, 9, 10],
'b': [10, 9, 0, 7, 6, 5, 4, 3, 2, 1],
'c': ['90.00%',
'77.78%',
'Error',
'42.86%',
'16.67%',
'-20.00%',
'-75.00%',
'100.00%',
'-350.00%',
'-900.00%']}
您正在经过一个pd。
这个答案表明你可以直接使用map()
df['c'] = (1-df['a']/df['b']).map('%{:,.2%}'.format)
您可以通过直接计算预期结果来节省异常管理:
return f"{1-(col1/col2):,.2%}" if col2 else "Error"
或(遵守函数的注释)
return f"{1-(col1/col2):,.2%}" if col2 else "100%"