Pandas DataFrame styler HTML display without index?

This can be done by using the hide_index() method such as below

print >> out, table.style.hide_index().apply(highlight_odd_row, axis=1).render()

I looked through the source code for pandas.formats.style.Styler, and couldn't find a super-easy way to do it. So instead here is a hacky way. Basically I tell the CSS for the table to not display elements with class row_heading and the top left empty box, which has classes blank level0.

import pandas as pd

def highlight_oddRow(s):
    return ['background-color: yellow' if s.name % 2 else '' for v in s]

table = pd.DataFrame(
    {'a': [3,9,8,0,2], 'b': [5,95, 9, 25,5], 'c': [23,54, 2, 3,5], 'row': [1, 2, 3, 4, 5]})

with open ('out.html','w') as out:
    # Get the styler for the table
    styler = table.style

    # Set the display to none for row headings, and the blank box in the top left corner for the column headings
    styler.set_table_styles(
        [{'selector': '.row_heading',
          'props': [('display', 'none')]},
         {'selector': '.blank.level0',
          'props': [('display', 'none')]}])

    print >> out, styler.apply(highlight_oddRow, axis=1).render()

The result:

enter image description here


Since this is the first question that popped up when I searched for this issue on Stack Overflow, I thought it would be good to share a recent development: on Nov-17 a PR was committed to the pandas repo that added the hide_index method to styler objects.

You can just call it before render:

def highlight_oddRow(s):
    return ['background-color: yellow' if s.name % 2 else '' for v in s]

table = pd.DataFrame(
    {'a': [3,9,8,0,2], 'b': [5,95, 9, 25,5], 'c': [23,54, 2, 3,5], 'row': [1, 2, 3, 4, 5]})

with open ('out.html','w') as out:
    print >> out, table.style.apply(highlight_oddRow, axis=1).hide_index().render()

Keep in mind the docs still claim these features are provisional and subject to change. More info here: https://pandas.pydata.org/pandas-docs/stable/style.html#Hiding-the-Index-or-Columns.

Tags:

Pandas

Html