pandaspandas-styles

Pandas DataFrame styler HTML display without index?


I have a pandas dataframe, I'm using the df.style object to make it highlight odd-numbered rows, so:

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).render()

However, this always prints out the index. Is there a way to tell it not to do this?


Solution

  • 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