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

使用pandas Styler修改DataFrame背景色时出现非唯一索引报错

报错根因

Pandas Styler渲染样式时强制要求DataFrame的索引为全局唯一值,你将重复的0、1标识序列设置为索引后,索引存在大量重复值,直接触发了该报错。如果用普通列时也触发相同报错,大概率是操作过程中误将该重复列设为了索引。

修正方案

不需要修改原表索引,直接将0、1标识作为普通列存在DataFrame中,着色时判断该列的值即可,还可以根据需求隐藏标识列:

# 生成着色标识列,保留原表唯一索引不变
color_index = []
for x in range(len(sql_query.cp)):
    if cod_port.index(sql_query.cp[x]) % 2 == 0:
        color_index.append(0)
    else:
        color_index.append(1)
sql_query['color_flag'] = color_index

# 着色函数直接判断每行的color_flag值
def highlight(row):
    if row['color_flag'] == 0:
        return ['background-color: white'] * len(row)
    else:
        return ['background-color: grey'] * len(row)

# 对原表应用样式,hide方法可隐藏不需要展示的标识列
sql_query.style.apply(highlight, axis=1).hide('color_flag', axis=1)

优化说明

原写法中*9固定列数的写法兼容性差,替换为*len(row)可自动适配任意列数的表格,无需手动调整数值。

内容的提问来源于stack exchange,提问作者Emanuele G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 21:54:05