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

如何在ipywidgets的interact函数中正确调用含DataFrame参数的函数

解决ipywidgets interact调用DataFrame绘图函数的错误

问题原因

你的df_plot函数需要接收df和num两个参数,但调用widgets.interact(df_plot, num=[0,1,2])时,没有固定df参数。interact会默认将所有未指定的参数都生成交互控件,而df是DataFrame类型,无法自动生成对应交互控件,因此触发错误。

修复方案

方案1:固定df参数,仅让num作为交互项

可以通过两种方式固定df参数,避免interact为其生成无效控件:

方法A:使用functools.partial绑定参数

from functools import partial

def f_interact():
    # 预先把df绑定到df_plot函数上
    plot_with_df = partial(df_plot, df=df)
    widgets.interact(plot_with_df, num=[0,1,2])

方法B:直接在interact中指定固定值

def f_interact():
    widgets.interact(df_plot, df=widgets.fixed(df), num=[0,1,2])

方案2:用列名作为下拉选项(更直观)

如果希望下拉框显示列名而非数字索引,可以调整函数和交互选项:

先修改df_plot函数:

def df_plot(df, col_name):
    df[col_name].plot()

再修改f_interact函数:

def f_interact():
    widgets.interact(df_plot, df=widgets.fixed(df), col_name=df.columns.tolist())

验证运行

调用f_interact()后,即可看到下拉选择框,选择不同选项会自动绘制对应列的折线图。

内容的提问来源于stack exchange,提问作者Martin Yordanov Georgiev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 08:54:57