Python Pandas Dataframes to_html:突出显示表格行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18096748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas Dataframes to_html: Highlighting table rows
提问by Charles Dillon
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>0</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?
所以我知道最后一行必须有<tr style=""background-color:#FF0000">
(或我想要的任何颜色)而不仅仅是<tr>
,但我真的不知道该怎么做是让我制作的表格发生这种情况。我不认为我可以用 to_html 函数本身来做到这一点,但是在创建表之后我该怎么做呢?
Any help is appreciated.
任何帮助表示赞赏。
采纳答案by Viktor Kerkez
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:
此外,较新版本的 Pandasdataframe
向表 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)
回答by paulperry
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<script>
放入其中。这使我能够使用https://github.com/christianbach/tablesorter呈现可排序的 Pandas 数据帧。
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 输出添加样式。
回答by volodymyr
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)