如何填充数据框中特定单元格的颜色?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何填充数据框中特定单元格的颜色?相关的知识,希望对你有一定的参考价值。

我创建了一个数据列,该列的列为Status。该列可以有两个值-SuccessFailed。我想用[Failed]值填充此列中的所有行。

请帮助我实现这一点?

示例:示例数据帧如下:

Master Job Name   Status

Settlement_limit  Success
Settlement_Trans  **Failed**
Ix_rm_bridge      Success
Unit_test         **Failed**
答案

您可以使用Styler.applymap逐元素应用样式功能

import pandas as pd
data = 'Master Job Name':['Settlement_limit', 'Settlement_Trans', 'Ix_rm_bridge', 'Unit_test'], 
        'Status':['Success', 'Failed', 'Success', 'Failed'] 

df = pd.DataFrame(data)

# function to fill font color
def fill_color(val):
    return 'color: red' if val=='Failed' else ''

df = df.style.applymap(fill_color, subset=['Status'])
df.to_excel('mysheet.xlsx') # excel sheet will be saved to present working directory, open the excel sheet to view changes

enter image description here

以上是关于如何填充数据框中特定单元格的颜色?的主要内容,如果未能解决你的问题,请参考以下文章