You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Pandas DataFrame非空单元格按列差异化着色

为Pandas DataFrame不同列的非空单元格设置不同颜色

你需要修改着色函数,通过布尔掩码判断单元格是否非空,仅对非空单元格应用指定颜色,空单元格保持默认白色。以下是修改后的完整代码:

import numpy as np
import pandas as pd

example = [['test1',1,2,'',''],['test2',3,4,'',''],['test3','','',5,6],['test4','','',7,8]]
df = pd.DataFrame(example, columns=['column1','column2','column3','column4','column5'])

def highlight_col(x):
    blue = 'background-color: lightblue'
    red = 'background-color: #ffcccb'
    # 初始化空样式DataFrame,默认所有单元格样式为空(白色背景)
    style_df = pd.DataFrame('', index=x.index, columns=x.columns)
    
    # 给column2、column3的非空单元格设置蓝色
    blue_cols_mask = x.iloc[:, 1:3] != ''
    style_df.iloc[:, 1:3] = np.where(blue_cols_mask, blue, '')
    
    # 给column4、column5的非空单元格设置红色
    red_cols_mask = x.iloc[:, 3:5] != ''
    style_df.iloc[:, 3:5] = np.where(red_cols_mask, red, '')
    
    return style_df

# 应用样式
df.style.apply(highlight_col, axis=None)

关键改动说明:

  • 用x.iloc[:, 1:3] != ''生成布尔掩码,标记column2、3中的非空单元格;同理处理column4、5。
  • 通过np.where批量为符合条件的单元格赋值样式,空单元格保持空字符串(对应默认白色背景)。
  • 修正了原代码中iloc[:,3:6]的索引错误,你的DataFrame只有5列(索引0-4),3:5刚好覆盖column4和column5。

内容的提问来源于stack exchange,提问作者Julie-Anne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 03:45:41