[英]Jupyter Notebook Widgets: Create dependent dropdowns
I want to create 2 dropdown widgets in my Jupyter Notebook. 我想在我的Jupyter笔记本中创建2个下拉小部件。 The dropdown content is taken from a dataframe.
下拉内容取自数据框。
Let's say I have a pandas dataframe consisting of 3 categorical variables 'a', 'b', 'c'. 假设我有一个由3个分类变量'a','b','c'组成的熊猫数据框。 'a' has 3 subtypes 'a1','a2' and 'a3'.
'a'有3个亚型'a1','a2'和'a3'。 'b' and 'c' are similar to a in the sense that they also have their own subtypes.
'b'和'c'类似于a,因为它们也有自己的子类型。 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.
我想创建2个下拉窗口小部件:第一个下拉窗口小部件将具有['a','b','c'],第二个下拉窗口小部件将显示子类型,具体取决于用户为第一个窗口小部件选择的变量。
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. 任何帮助表示赞赏。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.