Is there a way to format a column in a python pandas dataframe so that negative numbers are colored red and surrounded by parentheses?
I have found a way to do one or the other but not both. Any ideas?
Is there a way to format a column in a python pandas dataframe so that negative numbers are colored red and surrounded by parentheses?
I have found a way to do one or the other but not both. Any ideas?
 
    
     
    
    You can't have it as a number format and do what you want to do. you have to transform the numbers into strings. You can do it as follows
df=pd.DataFrame({'Numbers':[1,2,2,-1,3,-4]})
   Numbers
0        1
1        2
2        2
3       -1
4        3
5       -4
#function to color the values that starts with parenthesis
def color_parenthesis_red(val):   
    color = 'red' if val.startswith('(') else 'black'
    return 'color: %s' % color
#transform values into string and add parenthesis when they are negative
df['Numbers']=df['Numbers'].astype(str).apply(lambda x: f"({x})" if int(x)<0 else x)
df.style.applymap(color_negative_red)
