本文介绍了Python:如何在Bokeh select小部件中动态更改选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含国家和城市名称的数据框
I have a dataframe that contains the name of countries and cities
from bokeh.io import curdoc
from bokeh.layouts import row, column, widgetbox,layout
from bokeh.models import ColumnDataSource, Select
import pandas as pd
df = pd.DataFrame()
df['City'] = ['None', 'Paris', 'Lione', 'Rome','Milan', 'Madrid', 'Barcelona' ]
df['Country'] = ['None', 'France', 'France', 'Italy', 'Italy', 'Spain', 'Spain']
我想有两个小部件,一个用于国家,另一个用于城市.
I would like to have two widgets one for countries and the other for cities.
select_country = Select(title="Country", options=list(df['Country']), value = '')
select_city = Select(title = 'City', value = '', options = list(df['City']))
如果我选择其他Country
def update_layout(attr, old, new):
country_selected = select_country.value
tmp = df[df['Country']==country_selected]
select_city = Select(title = 'City', value = '', options = list(tmp['City']))
controls = widgetbox(select_country, select_city)
select_country.on_change('value', update_layout)
select_city.on_change('value', update_layout)
layout = column(row(controls))
curdoc().add_root(layout)
推荐答案
以下代码可动态更新第二个选择"小部件(Bokeh v1.1.0)中的选项
Here is a code that dynamically updates options in the second Select widget (Bokeh v1.1.0)
from bokeh.io import curdoc
from bokeh.models import Select, Column
import pandas as pd
df = pd.DataFrame()
df['France'] = ['Paris', 'Lione', 'Marseille']
df['Italy'] = ['Rome','Milan', 'Rimini']
df['Spain'] = ['Madrid', 'Barcelona', 'Bilbao']
df['Country'] = ['France', 'Italy', 'Spain']
select_country = Select(title="Country", options=list(df['Country']), value = 'France')
select_city = Select(title = 'Cities', value = 'Paris', options = list(df['France']))
def update_layout(attr, old, new):
country_selected = select_country.value
select_city.options = list(df[country_selected].values)
select_country.on_change('value', update_layout)
select_city.on_change('value', update_layout)
layout = Column(select_country, select_city)
curdoc().add_root(layout)
这篇关于Python:如何在Bokeh select小部件中动态更改选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!