13

I want to create 2 dropdown widgets in my Jupyter Notebook. The dropdown content is taken from a dataframe.

Let's say I have a pandas dataframe consisting of 3 categorical variables 'a', 'b', 'c'. 'a' has 3 subtypes 'a1','a2' and 'a3'. 'b' and 'c' are similar to a in the sense that they also have their own subtypes. I want to create 2 dropdown widgets: the first dropdown widget will have ['a','b','c'], and the second dropdown widget will display subtypes depending on what variable the user selects for the first widget.

I honestly have any idea how to do this. I'll try to write out some codes for this:

import pandas as pd
from IPython.display import *
import ipywidgets as widgets
from ipywidgets import *

# Create the dataframe
df = pd.DataFrame([['a1','a2','a3'],
             ['b1','b2','b3'],
             ['c1','c2','c3']], index = ['a','b','c']).transpose()

# Widgets
widget1 = Dropdown(options = ['a','b','c'])
display(widget1)
widget2 = Dropdown(???????)
display(widget2)

And depending on what I select for the two dropdown widgets, I want some function executed.

Any help is appreciated.

Hanazono Sakura
  • 651
  • 2
  • 8
  • 12

1 Answers1

26

I found out how to do this. I hope this helps for anyone else who's also looking to do the same thing.

x_widget = Dropdown(options = ['a','b','c'])
y_widget = Dropdown()

# Define a function that updates the content of y based on what we select for x
def update(*args):
    y_widget.options = df[x_widget.value].unique().tolist()
x_widget.observe(update)

# Some function you want executed
def random_function():
...

interact(random_function,
         x = x_widget,
         y = y_widget);
Hanazono Sakura
  • 651
  • 2
  • 8
  • 12
  • I encountered a similar situation where my second dropdown's option depends on the first dropdown's value. I've been trying to find a proper approach to address the question. Your answer is very close to what I need. Thanks a lot! – RandomWalker Oct 18 '19 at 16:29
  • 2
    Related section from docs: https://ipywidgets.readthedocs.io/en/latest/examples/Using%20Interact.html#Arguments-that-are-dependent-on-each-other – Sterling Jul 01 '22 at 16:47
  • How do you prevent a method for y_widget from executing – MadmanLee Aug 29 '22 at 23:37