【问题标题】:Percent format inside function函数内的百分比格式
【发布时间】: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


【解决方案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%']}

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

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

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

      或(遵守函数注释)

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

      【讨论】:

        猜你喜欢
        • 2010-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-03
        相关资源
        最近更新 更多