Jupyter Notebook 小部件:创建相关下拉列表
问题描述
我想在我的 Jupyter Notebook 中创建 2 个下拉小部件.下拉内容取自数据框.
I want to create 2 dropdown widgets in my Jupyter Notebook. The dropdown content is taken from a dataframe.
假设我有一个由 3 个分类变量a"、b"、c"组成的 pandas 数据框.'a' 有 3 个子类型 'a1'、'a2' 和 'a3'.'b' 和 'c' 与 a 相似,因为它们也有自己的子类型.我想创建 2 个下拉小部件:第一个下拉小部件将具有 ['a','b','c'],第二个下拉小部件将根据用户为第一个小部件选择的变量显示子类型.
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.
感谢任何帮助.
解决方案
我发现了如何做到这一点.我希望这对也希望做同样事情的其他人有所帮助.
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);
相关文章