我有一个熊猫数据框架:
arrays = [['Midland', 'Midland', 'Hereford', 'Hereford', 'Hobbs','Hobbs', 'Childress',
'Childress', 'Reese', 'Reese', 'San Angelo', 'San Angelo'],
['WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples)
df = pd.DataFrame(np.random.randn(12, 4), index=arrays,
columns=['00 UTC', '06 UTC', '12 UTC', '18 UTC'])从这里打印df的表格如下所示:

我想将“MOS”行中的所有值设置为某种颜色,并将左侧两个索引/标题列以及顶部标题行设置为与其他单元格不同的背景色。你知道我该怎么做吗?
发布于 2016-07-22 02:28:57
这需要几个步骤:
首先导入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,发疯吧!
发布于 2016-09-06 19:25:30
使用pandas的新styling功能(从0.17.1开始):
import numpy as np
import pandas as pd
arrays = [['Midland', 'Midland', 'Hereford', 'Hereford', 'Hobbs','Hobbs', 'Childress',
'Childress', 'Reese', 'Reese', 'San Angelo', 'San Angelo'],
['WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples)
df = pd.DataFrame(np.random.randn(12, 4), index=arrays,
columns=['00 UTC', '06 UTC', '12 UTC', '18 UTC'])
def highlight_MOS(s):
is_mos = s.index.get_level_values(1) == 'MOS'
return ['color: darkorange' if v else 'color: darkblue' for v in is_mos]
s = df.style.apply(highlight_MOS)
s

https://stackoverflow.com/questions/38511373
复制相似问题