首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用样式和css更改pandas dataframe html表python中文本的颜色。

使用样式和css更改pandas dataframe html表python中文本的颜色。
EN

Stack Overflow用户
提问于 2016-07-22 02:06:20
回答 2查看 24.8K关注 0票数 11

我有一个熊猫数据框架:

代码语言:javascript
复制
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”行中的所有值设置为某种颜色,并将左侧两个索引/标题列以及顶部标题行设置为与其他单元格不同的背景色。你知道我该怎么做吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-07-22 02:28:57

这需要几个步骤:

首先导入HTMLre

代码语言:javascript
复制
from IPython.display import HTML
import re

您可以通过to_html方法获取html pandas输出。

代码语言:javascript
复制
df_html = df.to_html()

接下来,我们将为将要创建的html表和样式生成一个随机标识符。

代码语言:javascript
复制
random_id = 'id%d' % np.random.choice(np.arange(1000000))

因为我们要插入一些样式,所以需要小心地指定此样式将仅用于我们的表。现在让我们将此代码插入到df_html

代码语言:javascript
复制
df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html)

并创建样式标签。这真的取决于你。我只是添加了一些悬停效果。

代码语言:javascript
复制
style = """
<style>
    table#{random_id} tr:hover {{background-color: #f5f5f5}}
</style>
""".format(random_id=random_id)

最后,显示它

代码语言:javascript
复制
HTML(style + df_html)

所有功能于一身。

代码语言:javascript
复制
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)

像这样使用它:

代码语言:javascript
复制
HTML_with_style(df.head())

代码语言:javascript
复制
HTML_with_style(df.head(), '<style>table {color: red}</style>')

代码语言:javascript
复制
style = """
<style>
    tr:nth-child(even) {color: green;}
    tr:nth-child(odd)  {color: aqua;}
</style>
"""
HTML_with_style(df.head(), style)

学习CSS,发疯吧!

票数 27
EN

Stack Overflow用户

发布于 2016-09-06 19:25:30

使用pandas的新styling功能(从0.17.1开始):

代码语言:javascript
复制
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

票数 29
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38511373

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档