这需要几个步骤:
首先导入HTML 和re
from IPython.display import HTML
import re
您可以通过to_html 方法获取html pandas 输出。
df_html = df.to_html()
接下来,我们将为要创建的 html 表格和样式生成一个随机标识符。
random_id = 'id%d' % np.random.choice(np.arange(1000000))
因为我们要插入一些样式,所以我们需要小心地指定这个样式只适用于我们的表格。现在让我们将其插入df_html
df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html)
并创建一个样式标签。这真的取决于你。我只是添加了一些悬停效果。
style = """
<style>
table#{random_id} tr:hover {{background-color: #f5f5f5}}
</style>
""".format(random_id=random_id)
最后展示一下
HTML(style + df_html)
功能一应俱全。
def HTML_with_style(df, style=None, random_id=None):
from IPython.display import HTML
import numpy as np
import re
df_html = df.to_html()
if random_id is None:
random_id = 'id%d' % np.random.choice(np.arange(1000000))
if style is None:
style = """
<style>
table#{random_id} {{color: blue}}
</style>
""".format(random_id=random_id)
else:
new_style = []
s = re.sub(r'</?style>', '', style).strip()
for line in s.split('\n'):
line = line.strip()
if not re.match(r'^table', line):
line = re.sub(r'^', 'table ', line)
new_style.append(line)
new_style = ['<style>'] + new_style + ['</style>']
style = re.sub(r'table(#\S+)?', 'table#%s' % random_id, '\n'.join(new_style))
df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html)
return HTML(style + df_html)
像这样使用它:
HTML_with_style(df.head())
HTML_with_style(df.head(), '<style>table {color: red}</style>')
style = """
<style>
tr:nth-child(even) {color: green;}
tr:nth-child(odd) {color: aqua;}
</style>
"""
HTML_with_style(df.head(), style)
学习 CSS 并发疯!