I'm creating tables using the pandas to_html function, and I'd like to be able to highlight the bottom row of the outputted table, which is of variable length. I don't have any real experience of html to speak of, and all I found online was this
<table border="1">
<tr style="background-color:#FF0000">
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>
So I know that the final row must have <tr style=""background-color:#FF0000">
(or whatever colour I want) rather than just <tr>
, but what I don't really know how to do is get this to occur with the tables I'm making. I don't think I can do it with the to_html function itself, but how can I do it after the table has been created?
Any help is appreciated.
In this tutorial, we are going to learn how to highlight a row in Pandas Dataframe in Python. To achieve this, we use apply() function of the Styler class.
You can do it in javascript using jQuery:
$('table tbody tr').filter(':last').css('background-color', '#FF0000')
Also newer versions of pandas add a class dataframe
to the table html so you can filter out just the pandas tables using:
$('table.dataframe tbody tr').filter(':last').css('background-color', '#FF0000')
But you can add your own classes if you want:
df.to_html(classes='my_class')
Or even multiple:
df.to_html(classes=['my_class', 'my_other_class'])
If you are using the IPython Notebook here is the full working example:
In [1]: import numpy as np
import pandas as pd
from IPython.display import HTML, Javascript
In [2]: df = pd.DataFrame({'a': np.arange(10), 'b': np.random.randn(10)})
In [3]: HTML(df.to_html(classes='my_class'))
In [4]: Javascript('''$('.my_class tbody tr').filter(':last')
.css('background-color', '#FF0000');
''')
Or you can even use plain CSS:
In [5]: HTML('''
<style>
.df tbody tr:last-child { background-color: #FF0000; }
</style>
''' + df.to_html(classes='df'))
The possibilities are endless :)
Edit: create an html file
import numpy as np
import pandas as pd
HEADER = '''
<html>
<head>
<style>
.df tbody tr:last-child { background-color: #FF0000; }
</style>
</head>
<body>
'''
FOOTER = '''
</body>
</html>
'''
df = pd.DataFrame({'a': np.arange(10), 'b': np.random.randn(10)})
with open('test.html', 'w') as f:
f.write(HEADER)
f.write(df.to_html(classes='df'))
f.write(FOOTER)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With