pythonpandasipywidgets

How to properly use function with dataframe argument in another ipywidget interact function


from ipywidgets import interact
import ipywidgets as widgets
import pandas as pd

I have a dataframe as below:

df = pd.DataFrame(index = [1,2,3], 
                   data = {'col1':[2,3,5],"col2":[2,5,2], "col3":[2,4,3]})

In addition I have a function df_plot that draws a line plot. Through a number argument I select which column to be drawn.

def df_plot(df, num):
    df.iloc[:,num].plot()

Trying to create another function f_interact that displays dropdown where I can choose which column to be plotted. df_plot is used in f_interact

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

I receive the following error

enter image description here

I most probably don't construct the set-up (functions and arguments) correctly. I went over ipywidgets documentation but cannot find a proper example. Can someone advise.


Solution

  • You are over-complicating things. Yu do not need the second function. Do this instead:

    from ipywidgets import interact
    import pandas as pd
    import matplotlib.pyplot as plt
    
    df = pd.DataFrame(index=[1, 2, 3], 
                      data={'col1': [2, 3, 5], "col2": [2, 5, 2], "col3": [2, 4, 3]})
    
    def df_plot(num):
        plt.figure() 
        df.iloc[:, num].plot(kind='line', title=f"Column {num + 1}")
        plt.show()
    
    interact(df_plot, num=(0, len(df.columns) - 1))
    

    which gives

    enter image description here