0

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?

David Erickson
  • 16,433
  • 2
  • 19
  • 35
jimbo1022
  • 39
  • 3
  • You could save time to a potential answerer by including the code that you have already used as well as some sample data. Please see: https://stackoverflow.com/help/how-to-ask . In regards to sample data and creating a minimum reproducible example, please see: https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples – David Erickson Jan 28 '21 at 04:34
  • Please add your dataframe, codes you have tried and what errors you have met – Nhiên Ngô Đình Jan 28 '21 at 04:35
  • [Styling](https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html) would be helpful for both conditions. – k33da_the_bug Jan 28 '21 at 04:35

1 Answers1

1

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)

enter image description here

Billy Bonaros
  • 1,671
  • 11
  • 18