使用styles和css更改pandas dataframe html表python中的文本颜色

HM1*_*M14 10 html css python dataframe pandas

我有一个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'])
Run Code Online (Sandbox Code Playgroud)

df从中打印的表格如下所示:在此输入图像描述

我想将"MOS"行中的所有值着色为左侧两个索引/标题列的特定颜色和颜色,以及顶部标题行的颜色与其余具有值的单元格的背景颜色不同.我有什么想法可以做到这一点?

vol*_*myr 25

使用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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


piR*_*red 22

这需要几个步骤:

首先进口HTMLre

from IPython.display import HTML
import re
Run Code Online (Sandbox Code Playgroud)

你可以html通过这种to_html方法获得大熊猫.

df_html = df.to_html()
Run Code Online (Sandbox Code Playgroud)

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

random_id = 'id%d' % np.random.choice(np.arange(1000000))
Run Code Online (Sandbox Code Playgroud)

因为我们要插入一些样式,所以我们需要注意指定此样式仅适用于我们的表.现在让我们把它插入到df_html

df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html)
Run Code Online (Sandbox Code Playgroud)

并创建一个样式标记.这真的取决于你.我刚添加了一些悬停效果.

style = """
<style>
    table#{random_id} tr:hover {{background-color: #f5f5f5}}
</style>
""".format(random_id=random_id)
Run Code Online (Sandbox Code Playgroud)

最后,显示它

HTML(style + df_html)
Run Code Online (Sandbox Code Playgroud)

功能齐全.

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)
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

HTML_with_style(df.head())
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

HTML_with_style(df.head(), '<style>table {color: red}</style>')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

style = """
<style>
    tr:nth-child(even) {color: green;}
    tr:nth-child(odd)  {color: aqua;}
</style>
"""
HTML_with_style(df.head(), style)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

学习CSS并疯狂!