David Yang
David Yang

Reputation: 2141

Ipywidgets Jupyter Notebook Interact Ignore Argument

Is there a way to have interact(f) ignore certain arguments in f? I believe it is getting confused by the fact that I have a default argument that I use to pass in a dataframe. Here is my function:

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)

Here is what I'm trying to do:

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

And here is the error I'm getting:

enter image description here

I hypothesize that interact somehow changes df_pnl into a string (since it gives a dropdown of the column headers in the interact output), and fails because it then tries to do df_pnl['Fulldate']..... on a string, which causes the error shown.

How do I get around this? Could I exclude that argument from my function while still having it work on the correct dataframe? Is there an option within interact to ignore certain arguments in the function?

Thanks

Upvotes: 2

Views: 2139

Answers (2)

Eduardo Pignatelli
Eduardo Pignatelli

Reputation: 173

You can use closures:

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)

Upvotes: 2

James Draper
James Draper

Reputation: 5310

So it is a little difficult to test this solution without a sample DataFrame but I think that functools.partial may be what you are looking for. Essentially partial allows you to define a new function with one of the keyword arguments or positional arguments loaded beforehand. Try the code below and see if works;

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)

Update:

You could also try ipywidgets the fixed function.

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))

Please comment below if this doesn't solve the problem.

Upvotes: 5

Related Questions