【问题标题】:Highlighting a single column using pandas Styling [duplicate]使用熊猫样式突出显示单个列[重复]
【发布时间】:2019-01-05 18:54:38
【问题描述】:

我创建了一个 pandas 数据框,然后我想将 background-color:red 添加到数据框中的任何选定列中,并在 html 中显示带有突出显示的列的数据框。

我的桌子形状如下:

import pandas as pd
import numpy as np

np.random.seed(24)
frame = pd.DataFrame({'A': np.linspace(1, 10, 10)})
frame = pd.concat([frame, pd.DataFrame(np.random.randn(10, 12), 
columns=list('BCDEFGHIJKLM'))],axis=1)

我在另一个类似问题的stackoverflow页面上找到了这个函数,但失败了:

(尝试按位置查找列)

def highlighter(col):
    r = 'background-color: red'
    df1 = pd.DataFrame('', index=col.index, columns=col.columns)
    df1.iloc[:, 8] = r
    return df1
tab = frame.style.apply(highlighter, axis=None).render()    
print(tab) 

这是我创建的另一个函数,但也失败了:

(尝试通过调用特定列名来查找列)

def highlighter(df, col):
    df = pd.DataFrame()
    return ['background-color:red' if col in df.columns else 'background-color:white']

tab = frame.style.apply(highlighter(col='C'), axis=None).render()
print(tab)

当我打印渲染的表格时,表格应该有一个背景色为红色的列,但我看不到这样的突出显示

【问题讨论】:

    标签: python html python-3.x pandas


    【解决方案1】:

    试试这个:

    def highlighter(col):
        r = 'background-color: red'
        df1 = pd.DataFrame('', index=col.index, columns=col.columns)
        df1.iloc[:, 8] = r
        return df1
    tab = frame.style.apply(highlighter, axis=None)
    
    with open('tab.html', 'w') as html:
        html.write(tab.render())
    

    【讨论】:

    • 原来解决方案相当简单,答案是here。 cmets中有对解决方案的说明
    • 当时为什么会发布这个问题?顺便说一句,我的就是这个问题的答案
    • 以上链接中的答案需要时间来更正,您在我删除之前发布答案。
    猜你喜欢
    • 2020-11-01
    • 1970-01-01
    • 2022-01-16
    • 2020-08-28
    • 1970-01-01
    • 2020-02-21
    • 2018-07-27
    • 2016-09-07
    • 1970-01-01
    相关资源
    最近更新 更多