【问题标题】:How to colorize text of a displayed dataframe when using ipywidgets for an interactive output?使用 ipywidgets 进行交互式输出时如何为显示的数据框的文本着色?
【发布时间】:2022-11-29 06:37:29
【问题描述】:

我正在研究这个问题来消费和比较两个计划之间的差异。长话短说,如果我们选择路线 A 或路线 B,我们将招致不同的结果。我使用 ipywidgets 创建了一些交互式按钮,这些按钮按预期控制 seaborn 线图。我遇到麻烦的地方是我想显示一个短数据框并根据一组标准进行着色。

我可以使用 display( df.style.applymap(color_defining_function) ) 在我的交互式输出之外着色。但是,当我尝试使用我定义的函数执行此操作时,该函数将采用交互式输入并过滤表格以显示相关信息,然后绘制表格,它将不再起作用。我试图在此处放置一些相关的示例代码。


import ipywidgets as widgets
import pandas as pd

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

# Make the interactions and get the dropdown values
slider = widgets.IntSlider( min= min(years), max= max(years) )

# Make the ui and define the function to create graphs. 
ui = widgets.HBox([slider])

# Define function that will return blue text for the year 2021
def color_blue_2021(val):
    color = 'blue' if val == '2021' else 'black'
    return 'color: %s' % color

# Draw table function that filters based on slider value and displays the table
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)

关于为什么这没有将 2021 的值突出显示为蓝色,有什么想法吗?

【问题讨论】:

    标签: pandas jupyter-notebook ipywidgets


    【解决方案1】:

    我想通了,我的数据框中的年份存储为 dtype 整数,而我正在寻找它等于 2021 年的字符串。它现在似乎可以按预期工作。

    【讨论】:

      猜你喜欢
      • 2010-09-17
      • 1970-01-01
      • 2022-06-22
      • 2017-02-28
      • 2020-04-16
      • 2013-11-21
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多