Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Dataframes to_html: Highlighting table rows

Tags:

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.

like image 959
Charles Dillon Avatar asked Aug 07 '13 07:08

Charles Dillon


People also ask

How do I highlight a row in pandas?

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.


1 Answers

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)
like image 190
Viktor Kerkez Avatar answered Sep 18 '22 09:09

Viktor Kerkez