pandas conditionally format field in bold pandas conditionally format field in bold pandas pandas

pandas conditionally format field in bold


This might help ...

Set up a dataframe

import pandas as pdimport numpy as npnp.random.seed(24)df = pd.DataFrame({'A': np.linspace(1, 10, 10)})df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],               axis=1)df.iloc[0, 2] = np.nan

create functional you can apply to add bold based on a condition of you define

def negative_bold(val):    bold = 'bold' if val < 0 else ''    return 'font-weight: %s' % bold

Apply the function to the style of the data frame

s = df.style.applymap(negative_bold)

Look at the dataframe, you should find all negative numbers are bold

enter image description here

I looked here https://mode.com/example-gallery/python_dataframe_styling/ and here https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html

EDIT Adding to this answer ...

Combining two styles

I have two functions, one to highlight yellow the number is negative and another make the number bold if negative

Negative_yellow

def negative_yellow(val):    color = 'yellow' if val < 0 else ''    return 'background-color:' + color  

Negative bold

def negative_bold(val):    bold = 'bold' if val < 0 else ''    return 'font-weight: %s' % bold

I apply the two the data frame like this

df.style.\    applymap(negative_yellow).\    applymap(negative_bold)

enter image description here

I imagine there are more elegant ways of doing this. Hope this helps :)