-1

我试图将数字分成两列,作为百分比并捕获任何 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% 也适用于我的实例。

4

3 回答 3

1

使用 zip 的简单解决方案:

[a / b for (a, b) in zip(la, lb)]

您可以将 替换为处理零除法情况a / b的函数调用 ( percent_diff),就像您拥有的一样,但无需管理列表迭代。

也就是说,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%']}
于 2021-10-18T18:30:39.217 回答
0

您将 pd.Series 传递到格式中,显然不支持该格式。

这个答案表明你可以使用map()

df['c'] = (1-df['a']/df['b']).map('%{:,.2%}'.format)

于 2021-10-18T18:40:33.340 回答
0

您可以通过直接计算预期结果来节省异常管理:

return f"{1-(col1/col2):,.2%}" if col2 else "Error"

或(遵守函数的注释)

return f"{1-(col1/col2):,.2%}" if col2 else "100%"
于 2021-10-18T18:58:33.860 回答