2017-08-18 12 views
1

Jupyterノートブックに2つのドロップダウンウィジェットを作成したいと思います。ドロップダウンの内容は、データフレームから取得されます。Jupyter Notebookウィジェット:依存ドロップダウンを作成

私はパンダのデータフレームを3つのカテゴリ変数 'a'、 'b'、 'c'で構成しています。 'a'には3つのサブタイプ 'a1'、 'a2'、 'a3'があります。 'b'と 'c'は、それ自身のサブタイプも持っているという意味でaと似ています。私は2つのドロップダウンウィジェットを作成したい:最初のドロップダウンウィジェットは['a'、 'b'、 'c']を持ち、2番目のドロップダウンウィジェットは、ユーザーが最初のウィジェットに対して選択する変数に応じてサブタイプを表示する。

私は正直なところ、これを行う方法を考えています。私はこのためにいくつかのコードを書くためにしようとするでしょう:

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) 

そして、私は2つのドロップダウンウィジェットの選択内容に応じて、私はいくつかの関数が実行します。

何か助けていただければ幸いです。

答えて

2

私はこれを行う方法を見つけました。私はこれが同じことをやろうとしている他の誰のためにも役立つことを願っています。

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); 
関連する問題