为 Pandas Dataframe.to_html() 的单列着色

swa*_*onk 3 python dataframe pandas

在将其标记为重复之前,我已经尝试了以下主题中的代码,但到目前为止没有一个对我有用:

[为 pandas 数据框的一列着色]

[根据多种条件格式化 panda 数据框中单元格的颜色]

[如何在 python 数据框中为选定的列着色?]

我有代码可以生成三个 pandas 数据框,如下所示:

         RowName   Orders   Market  StartTime  StopTime
Status
good     A          9       gold    10:00:00    10:09:45
                             .         
                             .
                             .
bad      B          60      silver  07:54:43    08:02:12

         RowName   Orders   Market  StartTime  StopTime
Status
good     E          19      plat.    10:00:00    10:09:45
                             .         
                             .
bad      F          54      mercury  07:54:43    08:02:12

         RowName   Orders   Market  StartTime  StopTime
Status
great     D          3       alum.   10:00:00    10:09:45
                             .         
                             .
ok        C          70      bronze  07:54:43    08:02:12
Run Code Online (Sandbox Code Playgroud)

其中该Status列设置为每个帧的索引

对于每个帧,我想突出显示StartTime具有该值#D42A2A(又名红色)的列,无论给定单元格中的值是什么。

如何才能做到这一点?

最近失败的尝试:

  1. def column_style(col): if col.Name == 'StartTime': return pd.Series('bgcolor: #d42a2a', col.index)

  2. def col_color(data): color = 'red' if data != '' else 'black' return 'color: %s' %color frame.style.applymap(col_color, subset=['StartTime'])

但这也失败了。

笔记:

  1. 我在 Linux shell 中使用 VI

  2. 整个脚本由 IE(Internet Explorer)调用,因此脚本的输出是 html

  3. 我正在使用 BS(beautifulsoup)从几个网站抓取数据,并将结果聚合到一个页面上{*在抓取初始网站并创建所需的网站(称为 Page1)之后,我尝试在同一脚本中抓取 Page1 并通过该方法添加 html 行.attrs,但这“失败”,即网络服务器在运行期间超时}

Sco*_*ton 5

让我们试试这个:

import pandas as pd
import numpy as np

np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})

df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
               axis=1)
df.iloc[0, 2] = np.nan

def highlight_column(s, col):
    return ['background-color: #d42a2a' if s.name == col else '' for v in s.index]

df.style.apply(highlight_column, col = 'B')
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述