我正在尝试格式化pandas系列:对于所有值,我想添加千位分隔符并将小数点限制为两位。另外,对于负值,我想用括号把它括起来,而不是用-
符号。所以输出应该看起来像'20,000.00', '(152,111.12)'
等
我知道f-string方法有效因为当我运行
时val = 20000
f'{val:,.2f}'
它给了我正确的结果'20,000.00'
。但是当我尝试创建一个函数并将其应用于Pandas中的整个列时:
def format_pnl(value):
# Format the value as a string with thousand separators and 2 decimal places
formatted_value = f"{value:, .2f}"
# If the value is negative, wrap it in parentheses
if value < 0:
formatted_value = f"({formatted_value})"
return formatted_value
我得到ValueError:无效的格式说明符。这对我来说真是难以置信,因为格式说明符绝对有效。我遗漏了什么?
您在逗号和句号之间添加了空格。
您可以很容易地做到这一点,并将其应用到您的特定列
import pandas as pd
df = pd.DataFrame([100000, 1113, 510101.05, 6456464, -846464.12])
def format_pnl(value):
return f"{value:,.2f}" if value >= 0 else f"({abs(value):,.2f})"
# Specify the specific column you want here
df[0] = df[0].apply(format_pnl)
display(df)
0
0 100,000.00
1 1,113.00
2 510,101.05
3 6,456,464.00
4 (846,464.12)