Python:如何在Bokeh select小部件中动态更改选项?

时间:2019-05-23 15:03:15

标签: python bokeh

我有一个包含国家和城市名称的数据框

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']

我想有两个小部件,一个用于国家,另一个用于城市。

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)

1 个答案:

答案 0 :(得分:1)

这是一个代码,用于动态更新第二个“选择”小部件(Bokeh v1.1.0)中的选项

from bs4 import BeautifulSoup, Tag

markup = """
<dblp>
<incollection> 
<author>Philippe Balbiani</author> 
<author>Valentin Goranko</author> 
<author>Ruaan Kellerman</author> 
<booktitle>Handbook of Spatial Logics</booktitle> 
</incollection>
<incollection> 
<author>Jochen Renz</author> 
<author>Bernhard Nebel</author> 
<booktitle>Handbook of AI</booktitle> 
</incollection>
</dblp>
"""

author = []
elem_dic = []

soup = BeautifulSoup(markup, 'xml')
res = soup.find_all('incollection')
for each in res:
    for child in each.children:
        if not isinstance(child, Tag):
            continue
        if child.name == 'author':
            author.append(child.text)
        else:
            elem_dic.extend(zip(author, [child.text] * len(author)))
            author = []

print(tuple(elem_dic))