Pandas DataFrame样式HTML显示没有索引?

Bri*_*tow 3 html pandas

我有一个pandas数据帧,我正在使用df.style对象使其突出显示奇数行,所以:

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()
Run Code Online (Sandbox Code Playgroud)

但是,这总是打印出索引.有没有办法告诉它不要这样做?

小智 11

这可以通过使用以下hide_index()方法来完成

print >> out, table.style.hide_index().apply(highlight_odd_row, axis=1).render()
Run Code Online (Sandbox Code Playgroud)


Tom*_*ias 9

由于这是我在Stack Overflow上搜索此问题时出现的第一个问题,我认为分享最近的开发会很好:在11月17日,PR已经致力于将hide_index方法添加到styler对象的pandas repo .

你可以在渲染之前调用它:

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()
Run Code Online (Sandbox Code Playgroud)

请记住,文档仍然声称这些功能是临时的,可能会有所变化.更多信息:https://pandas.pydata.org/pandas-docs/stable/style.html#Hiding-the-Index-or-Columns.


小智 7

我查看了 的源代码pandas.formats.style.Styler,但找不到一种超级简单的方法。所以这里是一种hacky方式。基本上我告诉表格的 CSS 不显示带有 class 的元素row_heading和左上角的空框,它有 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()
Run Code Online (Sandbox Code Playgroud)

结果:

在此处输入图片说明