Pandas Dataframes to_html:突出显示表行

时间:2023-01-05 22:57:43

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

我正在使用pandas to_html函数创建表,我希望能够突出显示输出表的底行,它具有可变长度。我没有任何关于html的真实经验,我在网上找到的就是这个

<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?

所以我知道最后一行必须有(或者我想要的任何颜色)而不仅仅是,但我真的不知道该怎么做就是得到这与我正在制作的表格一起发生。我不认为我可以使用to_html函数本身,但是如何在创建表格后执行此操作?

Any help is appreciated.

任何帮助表示赞赏。

3 个解决方案

#1


18  

You can do it in javascript using jQuery:

你可以使用jQuery在javascript中完成它:

 $('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:

另外,较新版本的pandas会将类数据帧添加到表html中,因此您可以使用以下方法过滤掉pandas表:

 $('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:

如果您使用的是IPython Notebook,那么这是一个完整的工作示例:

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:

或者您甚至可以使用纯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

编辑:创建一个html文件

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)

#2


19  

Since pandas has styling functionality now, you don't need JavaScript hacks anymore. This is a pure pandas solution:

由于pandas现在具有样式功能,因此您不再需要JavaScript hacks。这是一个纯粹的熊猫解决方案:

import pandas as pd

df = []
df.append(dict(date='2016-04-01', sleep=11.2, calories=2740))
df.append(dict(date='2016-04-02', sleep=7.3, calories=3600))
df.append(dict(date='2016-04-03', sleep=8.3, calories=3500))

df = pd.DataFrame(df)

def highlight_last_row(s):
    return ['background-color: #FF0000' if i==len(s)-1 else '' for i in range(len(s))]

s = df.style.apply(highlight_last_row)

Pandas Dataframes to_html:突出显示表行

#3


4  

I can't get @Viktor's "full working example" to work in ipython (jupyter) because the last line is what gets rendered, but moving the HTML rendering after the Javascript line did not work for me.

我不能让@Viktor的“完整工作示例”在ipython(jupyter)中工作,因为最后一行是渲染的内容,但在Javascript行之后移动HTML渲染对我来说不起作用。

The "plain CSS" example does work, and we can even put a Javascript <script> in there. This allowed me to render a sortable Pandas dataframe using https://github.com/christianbach/tablesorter .

“普通CSS”示例确实有效,我们甚至可以在其中放置Javascript

Here is a full example:

这是一个完整的例子:

df = pd.DataFrame({'a': np.arange(10), 'b': np.random.randn(10)})
from IPython.display import HTML, Javascript
HTML('''<script src='./tablesort/tablesort.min.js'></script>
<script src='./tablesort/src/sorts/tablesort.number.js'></script>
<script>
new Tablesort(document.getElementById('sort'));
</script>
'''+ df.to_html(classes ='sort" id = "sort'))

Note that the .js files are local. Referring directly to the github raw code will not work as the MIME type is plain/txt .

请注意,.js文件是本地的。直接引用github原始代码将不起作用,因为MIME类型是plain / txt。

Update: I just noticed that Pandas v0.17.1 released a feature to add style to the DataFrame HTML output.

更新:我刚刚注意到Pandas v0.17.1发布了一项功能,可以为DataFrame HTML输出添加样式。

#1


18  

You can do it in javascript using jQuery:

你可以使用jQuery在javascript中完成它:

 $('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:

另外,较新版本的pandas会将类数据帧添加到表html中,因此您可以使用以下方法过滤掉pandas表:

 $('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:

如果您使用的是IPython Notebook,那么这是一个完整的工作示例:

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:

或者您甚至可以使用纯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

编辑:创建一个html文件

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)

#2


19  

Since pandas has styling functionality now, you don't need JavaScript hacks anymore. This is a pure pandas solution:

由于pandas现在具有样式功能,因此您不再需要JavaScript hacks。这是一个纯粹的熊猫解决方案:

import pandas as pd

df = []
df.append(dict(date='2016-04-01', sleep=11.2, calories=2740))
df.append(dict(date='2016-04-02', sleep=7.3, calories=3600))
df.append(dict(date='2016-04-03', sleep=8.3, calories=3500))

df = pd.DataFrame(df)

def highlight_last_row(s):
    return ['background-color: #FF0000' if i==len(s)-1 else '' for i in range(len(s))]

s = df.style.apply(highlight_last_row)

Pandas Dataframes to_html:突出显示表行

#3


4  

I can't get @Viktor's "full working example" to work in ipython (jupyter) because the last line is what gets rendered, but moving the HTML rendering after the Javascript line did not work for me.

我不能让@Viktor的“完整工作示例”在ipython(jupyter)中工作,因为最后一行是渲染的内容,但在Javascript行之后移动HTML渲染对我来说不起作用。

The "plain CSS" example does work, and we can even put a Javascript <script> in there. This allowed me to render a sortable Pandas dataframe using https://github.com/christianbach/tablesorter .

“普通CSS”示例确实有效,我们甚至可以在其中放置Javascript

Here is a full example:

这是一个完整的例子:

df = pd.DataFrame({'a': np.arange(10), 'b': np.random.randn(10)})
from IPython.display import HTML, Javascript
HTML('''<script src='./tablesort/tablesort.min.js'></script>
<script src='./tablesort/src/sorts/tablesort.number.js'></script>
<script>
new Tablesort(document.getElementById('sort'));
</script>
'''+ df.to_html(classes ='sort" id = "sort'))

Note that the .js files are local. Referring directly to the github raw code will not work as the MIME type is plain/txt .

请注意,.js文件是本地的。直接引用github原始代码将不起作用,因为MIME类型是plain / txt。

Update: I just noticed that Pandas v0.17.1 released a feature to add style to the DataFrame HTML output.

更新:我刚刚注意到Pandas v0.17.1发布了一项功能,可以为DataFrame HTML输出添加样式。