Jupyter Notebook小部件:创建依赖项下拉列表 [英] Jupyter Notebook Widgets: Create dependent dropdowns

查看:497
本文介绍了Jupyter Notebook小部件:创建依赖项下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Jupyter Notebook中创建2个下拉窗口小部件.下拉内容取自数据框.

假设我有一个由3个类别变量"a","b","c"组成的熊猫数据框. 'a'具有3个子类型'a1','a2'和'a3'. 'b'和'c'在也具有自己的子类型的意义上类似于a.我想创建2个下拉窗口小部件:第一个下拉窗口小部件将具有['a','b','c'],第二个下拉窗口小部件将显示子类型,具体取决于用户为第一个窗口小部件选择的变量. >

老实说,我不知道该怎么做.我将尝试为此编写一些代码:

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)

根据我为两个下拉小部件选择的内容,我希望执行一些功能.

感谢您的帮助.

解决方案

我发现了如何做到这一点.我希望这对其他也想做同样事情的人有所帮助.

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);

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.

解决方案

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);

这篇关于Jupyter Notebook小部件:创建依赖项下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆