I am trying to format a pandas series: for all values, I want to add thousands separators and limit decimal places to two. In addition, for negative values, instead of a -
sign, I want to enclose it with parentheses. So output should look like '20,000.00', '(152,111.12)'
etc.
I know the f-string method works because when I run
val = 20000
f'{val:,.2f}'
It gives me the correct result '20,000.00'
. But when I tried to create a function and apply it to an entire column in 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
I got the ValueError: Invalid format specifier. This is really mind boggling to me since the format specifier absolutely works. What am I missing here?