Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

Is there a way to format a column in a python pandas dataframe so that negative numbers are colored red and surrounded by parentheses?

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?

question from:https://stackoverflow.com/questions/65931005/is-there-a-way-to-format-a-column-in-a-python-pandas-dataframe-so-that-negative

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...