Pandas dataframe.to_html() - edit text color and add background color of header columns

2.1k views Asked by At

I am exporting a pandas dataframe as an html table and have been playing around with styling the the header columns in the final table. Here is an example dataframe I have generated:

x = np.arange(0,100,5)
y = np.arange(0,20,1)
example_df = pd.DataFrame(x,y).head(10).reset_index()
example_df.columns = ['X Column', 'Y Column']

I have been able to edit the header text color with the following code:

example_df = example_df.to_html(index=False).replace('<th>','<th style = "color", "White">')

I have also been able to separately alter the background color using the following code:

example_df = example_df.to_html(index=False).replace('<th>','<th style = "background-color", "RoyalBlue">')

While I have been able to alter the column header text color and background color separately, I have not been able to alter both simultaneously. Is there a better way to accomplish this so that I am able to alter both the text color and background color rather than choosing between only altering one or the other? Thanks!

1

There are 1 answers

0
Shirish Dubey On

This will work -

> example_df.to_html(index=False).replace('<th>','<th style =
> "background-color: royalblue; color: white">')