Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bold column in pandas DataFrame to_html

I am trying to return df.to_html() with one bold column. I have only tried

df = pd.DataFrame({'important_column': [1,2,3,4], 
                   'dummy_column': [5,6,7,8]})

def some_function()
      df.apply(lambda x: '<b>' + str(df['important_column']) + '</b>', axis=1)
      return [df.to_html()]

But it doesn't seem to work. Does any one know a practical solution?

like image 945
Finrod Felagund Avatar asked Jan 27 '23 12:01

Finrod Felagund


1 Answers

You can use a df.style.set_properties and then .render() which'll prefix the normal table output from .to_html() with an appropriate style element. (note this does not physically wrap your text elements inside a <b> or <strong> or whatever tags you wish but purely provides styling for those cells - which may or may not be what you want depending on the use case)

html = df.style.set_properties(
    subset=['important_column'], 
    **{'font-weight': 'bold'}
).render()

(example shown in jupyter notebook)

enter image description here

like image 77
Jon Clements Avatar answered Jan 30 '23 01:01

Jon Clements