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

如何修改Pandas中已应用样式的DataFrame:添加百分比后缀

解决Pandas Styler对象无法添加%后缀的问题

问题场景

现有如下结构的DataFrame:

Server        Env.    Model   Percent_Utilized
server123     Prod     Cisco.       50
server567.    Prod     Cisco.       80
serverabc.    Prod     IBM.         100
serverdwc.    Prod     IBM.         45
servercc.     Prod      Hitachi.    25
Avg                                60

server123Uat  Uat     Cisco.       40
server567u    Uat     Cisco.       30
serverabcu    Uat     IBM.         80
serverdwcu    Uat     IBM.         45
serverccu     Uat     Hitachi      15
Avg                               42

已通过以下代码为Percent_Utilized列添加背景色样式:

def color(val):
    if val > 80:
        color = 'red'
    elif val > 50 and val <= 80:
        color = 'yellow'
    else:
        color = 'green'
    return 'background-color: %s' % color

df_new = df.style.applymap(color, subset=["Percent_Utilized"])

尝试通过df_new['Percent_Utilized'] = df_new['Percent_Utilized'].astype(str) + '%'为数值添加%后缀时,报错:TypeError: 'Styler' object is not subscriptable。

错误原因

df_new是Styler对象,并非原始DataFrame。Styler是Pandas用于渲染表格样式的包装器,不支持像DataFrame那样用[]直接访问或修改列数据,必须使用Styler提供的专属方法调整显示格式。

解决方案

推荐使用Styler的format()方法,既能保留原始数值用于背景色判断,又能在显示时添加%后缀,无需修改原始DataFrame数据:

def color(val):
    if val > 80:
        color = 'red'
    elif val > 50 and val <= 80:
        color = 'yellow'
    else:
        color = 'green'
    return 'background-color: %s' % color

# 先应用背景色样式,再设置列显示格式
df_new = df.style.applymap(color, subset=["Percent_Utilized"]) \
           .format({'Percent_Utilized': '{:.0f}%'})

补充说明

  • '{:.0f}%'表示将数值格式化为整数后添加%后缀,若需保留小数(如1位小数),可改为'{:.1f}%'。
  • 若DataFrame中Avg行的Percent_Utilized为字符串类型(非数值),可通过自定义函数兼容处理:
def format_percent(val):
    try:
        return f"{int(val)}%"
    except (ValueError, TypeError):
        return val

df_new = df.style.applymap(color, subset=["Percent_Utilized"]) \
           .format({'Percent_Utilized': format_percent})

处理后,表格会显示带%后缀的数值,同时保留原有的背景色样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 14:05:07