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

使用ipywidgets交互式输出时,DataFrame指定文本上色失效原因排查

问题:ipywidgets交互场景下DataFrame样式上色失效

在对比两个方案差异的工作中,使用ipywidgets创建交互按钮控制seaborn折线图正常,但在交互函数内显示小型DataFrame并按特定条件为文本上色时失效。交互外通过display(df.style.applymap(颜色定义函数))可实现上色,放入交互函数后却无法生效,示例代码如下:

import ipywidgets as widgets
import pandas as pd

years = range(2020, 2025, 1)
df = pd.DataFrame(years, columns=['Years'])

# 创建滑块交互组件
slider = widgets.IntSlider(min=min(years), max=max(years))

# 构建UI
ui = widgets.HBox([slider])

# 定义颜色函数:2021年文本设为蓝色
def color_blue_2021(val):
    color = 'blue' if val == '2021' else 'black'
    return 'color: %s' % color

# 交互函数:根据滑块值过滤表格并显示
def draw_table(year):
    displayed_df = df.loc[ df['Years'] <= year]
    return display( displayed_df.style.applymap(color_blue_2021), clear = True )

table_out = widgets.interactive(draw_table, year = slider)
display(ui, table_out)

原因分析

核心问题是数据类型不匹配:

  • DataFrame中Years列的数值是整数类型(由range()生成,转成DataFrame后保持int类型)
  • 颜色判断函数color_blue_2021中用字符串'2021'和数值比较,val == '2021'永远为False,导致所有文本都显示黑色。

另外,widgets.interactive的函数返回方式建议直接在函数内调用display(),而非return,避免输出处理异常。

修正后的代码

import ipywidgets as widgets
import pandas as pd

years = range(2020, 2025, 1)
df = pd.DataFrame(years, columns=['Years'])

slider = widgets.IntSlider(min=min(years), max=max(years))
ui = widgets.HBox([slider])

# 修改判断条件:使用整数2021匹配
def color_blue_2021(val):
    color = 'blue' if val == 2021 else 'black'
    return 'color: %s' % color

def draw_table(year):
    displayed_df = df.loc[ df['Years'] <= year]
    # 直接调用display,无需return
    display(displayed_df.style.applymap(color_blue_2021), clear=True)

table_out = widgets.interactive(draw_table, year=slider)
display(ui, table_out)

补充说明

如果需要基于字符串判断,也可以把数值转成字符串后比较:

def color_blue_2021(val):
    color = 'blue' if str(val) == '2021' else 'black'
    return 'color: %s' % color

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 03:31:36