【问题标题】:Ipywidgets Jupyter Notebook Interact Ignore ArgumentIpywidgets Jupyter Notebook Interact Ignore Argument
【发布时间】:2017-08-02 22:09:19
【问题描述】:

有没有办法让interact(f) 忽略f 中的某些参数?我相信我有一个用于传递数据帧的默认参数这一事实让我感到困惑。这是我的功能:

def show_stats(start,end,df_pnl=df_pnl):
    mask = df_pnl['Fulldate'] >= start & df_pnl['FullDate'] <= end
    df_pnl = df_pnl[mask]
    #do some more transformations here
    display(df_pnl)

这是我想要做的:

interact(show_stats,start=start_str,end=today_str)

这是我得到的错误:

我假设interact 以某种方式将df_pnl 更改为字符串(因为它在交互输出中提供了列标题的下拉列表),并且失败了,因为它随后尝试对字符串执行df_pnl['Fulldate'].....,这导致显示的错误。

我该如何解决这个问题?我可以从我的函数中排除该参数,同时仍然让它在正确的数据帧上工作吗?交互中是否有一个选项可以忽略函数中的某些参数?

谢谢

【问题讨论】:

  • 你有没有尝试过我的解决方案?
  • 如果您在回答问题时感到困惑,此链接有一些 helpful tips
  • 感谢您的回答。如果您不介意,我将不胜感激。我赞成这个问题,所以它有点正确?谢谢老兄:)

标签: python-3.x jupyter-notebook ipython-notebook jupyter ipywidgets


【解决方案1】:

因此,在没有示例 DataFrame 的情况下测试此解决方案有点困难,但我认为 functools.partial 可能是您正在寻找的。本质上,partial 允许您使用预先加载的关键字参数或位置参数之一定义一个新函数。试试下面的代码,看看是否有效;

from functools import partial

def show_stats(start, end, df_pnl):
    mask = df_pnl['Fulldate'] >= start & df_pnl['FullDate'] <= end
    df_pnl = df_pnl[mask]
    #do some more transformations here
    display(df_pnl)

# Define the new partial function with df_pnl loaded.
show_stats_plus_df = partial(show_stats, df_pnl=YOUR_DATAFRAME)

interact(show_stats_plus_df, start=start_str, end=today_str)

更新:

您也可以尝试使用 ipywidgets fixed 函数。

from ipywidgets import fixed

def show_stats(start, end, df_pnl):
    mask = df_pnl['Fulldate'] >= start & df_pnl['FullDate'] <= end
    df_pnl = df_pnl[mask]
    #do some more transformations here
    display(df_pnl)

interact(show_stats, start=start_str, end=today_str, df_pnl=fixed(df_pnl))

如果这不能解决问题,请在下方评论。

【讨论】:

  • 我很困惑,因为这对我不起作用:python def g(dat, x): print("dat={dat} from inside g") return dat from functools import partial, update_wrapper def wrapped_partial(func, *args, **kwargs): partial_func = partial(func, *args, **kwargs) update_wrapper(partial_func, func) return partial_func g_plus_dat = wrapped_partial(g, dat='a') interact(g_plus_dat, x=10) 给了ValueError: cannot find widget or abbreviation for argument: 'dat'
【解决方案2】:

你可以使用闭包:

from ipywidgets import interact

def show_stats(start, end, df_pnl)
  @interact(start=start_str, end=today_str)
  def _show_stats(start, end):
      mask = df_pnl['Fulldate'] >= start & df_pnl['FullDate'] <= end
      df_pnl = df_pnl[mask]
      #do some more transformations here
      display(df_pnl)

【讨论】:

    猜你喜欢
    • 2021-02-06
    • 2019-02-18
    • 2017-10-04
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 2016-05-01
    相关资源
    最近更新 更多