我試圖將數字分成兩列,作為百分比并捕獲任何 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% 也適用于我的實體。
uj5u.com熱心網友回復:
使用 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%']}
uj5u.com熱心網友回復:
您將 pd.Series 傳遞到格式中,這顯然不受支持。
這個答案表明你可以使用map()
df['c'] = (1-df['a']/df['b']).map('%{:,.2%}'.format)
uj5u.com熱心網友回復:
您可以通過直接計算預期結果來節省例外管理:
return f"{1-(col1/col2):,.2%}" if col2 else "Error"
或(遵守函式的注釋)
return f"{1-(col1/col2):,.2%}" if col2 else "100%"
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/329436.html
