Search code examples
dataframedatagridipywidgets

using ipywidgets SelectMultiple on a dataframe


import pandas as pd
import numpy as np
import ipywidgets as widgets
from IPython.display import display 

a = ['Banking', 'Auto', 'Life', 'Electric', 'Technology', 'Airlines', 
'Healthcare']
df = pd.DataFrame(np.random.randn(7, 4), columns = list('ABCD'))
df.index = a

df.head(7)


dropdown = widgets.SelectMultiple(
                        options=df.index,
                        description='Sector',
                        disabled=False,
                        layout={'height':'100px', 'width':'40%'})
display(dropdown)

I want to create a function where I can filter the df by Sector. i.e say I select Airlines, Banking and Electric from the display(dropdown) and it returns a dataframe of the selected sectors only.


Solution

  • Try something like this, I have used a global variable to demonstrate in this case, but I would normally wrap up the functionality in a class so you always have access to the filtered dataframe.

    Rather than use interact I have used .observe on the Selection widget.

    import pandas as pd
    import numpy as np
    import ipywidgets as widgets
    from IPython.display import display, clear_output
    
    a = ['Banking', 'Auto', 'Life', 'Electric', 'Technology', 'Airlines', 
    'Healthcare']
    df = pd.DataFrame(np.random.randn(7, 4), columns = list('ABCD'), index=a)
    
    filtered_df = None
    
    
    dropdown = widgets.SelectMultiple(
                            options=df.index,
                            description='Sector',
                            disabled=False,
                            layout={'height':'100px', 'width':'40%'})
    
    def filter_dataframe(widget):
        global filtered_df
        selection = list(widget['new'])
    
        with out:
            clear_output()
            display(df.loc[selection])
            filtered_df = df.loc[selection]
    
    out = widgets.Output()
    dropdown.observe(filter_dataframe, names='value')
    display(dropdown)
    display(out)