使用样式和 css 更改 Pandas 数据框 html table python 中文本的颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38511373/
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
Change the color of text within a pandas dataframe html table python using styles and css
提问by HM14
I have a pandas dataframe:
我有一个Pandas数据框:
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'])
The table that prints df
from this looks like this:
I would like to color all of the values in the 'MOS' rows a certain color and color the left two index/header columns as well as the top header row a different background color than the rest of the cells with values in them. Any ideas how I can do this?
我想将“MOS”行中的所有值着色为某种颜色,并为左侧的两个索引/标题列以及顶部标题行着色与其他具有值的单元格不同的背景颜色。任何想法我怎么能做到这一点?
回答by piRSquared
This takes a few steps:
这需要几个步骤:
First import HTML
and re
首先导入HTML
和re
from IPython.display import HTML
import re
You can get at the html
pandas puts out via the to_html
method.
您可以html
通过该to_html
方法获取pandas 。
df_html = df.to_html()
Next we are going to generate a random identifier for the html table and style we are going to create.
接下来,我们将为我们将要创建的 html 表和样式生成一个随机标识符。
random_id = 'id%d' % np.random.choice(np.arange(1000000))
Because we are going to insert some style, we need to be careful to specify that this style will only be for our table. Now let's insert this into the df_html
因为我们要插入一些样式,所以我们需要小心地指定这种样式将只用于我们的表。现在让我们把它插入df_html
df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html)
And create a style tag. This is really up to you. I just added some hover effect.
并创建一个样式标签。这真的取决于你。我只是添加了一些悬停效果。
style = """
<style>
table#{random_id} tr:hover {{background-color: #f5f5f5}}
</style>
""".format(random_id=random_id)
Finally, display it
最后显示一下
HTML(style + df_html)
Function all in one.
功能一应俱全。
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)
Use it like this:
像这样使用它:
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)
Learn CSS and go nuts!
学习 CSS 并发疯!
回答by volodymyr
Using pandas new stylingfunctionality (since 0.17.1):
使用 pandas 新样式功能(自 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