我有一个由八列组成的 df 。我对其中两个感兴趣:“Id”和“Description”。 “Id”包含数字值,而“Description”包含字符串值(例如“高紧急情况”、“低紧急情况”、“区域 1”)。我想使用包含选定单词列表的下拉菜单来过滤 df。例如,在下拉菜单中选择单词“emergency”,结果应该是一个新的 df,仅过滤“Description”列中包含单词“emergency”的行。
过滤后,我想在条形图中绘制剩余 Id 的出现次数(使用 value_counts() 方法进行计数),该条形图根据下拉菜单中所选的关键字进行更新。
我在这里报告我到目前为止编写的代码(df已经导入):
import ipywidgets
from bokeh.io import push_notebook
from bokeh.plotting import figure
from bokeh.io import output_notebook, show, reset_output
from bokeh.models import Range1d
output_notebook()
# drop-down widget
drop_down = ipywidgets.Dropdown(options=['emergency',
'zone'],
description='Keyword:'
)
#data. I have problems here because I am passing alarm_count that is defined later in the function
x_bar_data_ipyw = alarm_count.IdAlarm.astype(str)
y_bar_data_ipyw = alarm_count.Count
# figure and plot
bar_chart_interactive = figure(x_range=x_bar_data_ipyw, plot_height=300)
bar_ipyw = bar_chart_interactive.vbar(x_bar_data_ipyw, top=y_bar_data_ipyw, color='green', width=0.5)
bar_chart_interactive.y_range=Range1d(0, 18)
# function - bar chart
def filter(word):
if word == 'emergency':
alarm_count = []
alarm_count = df[df.Description.str.contains(word)].IdAlarm.value_counts().reset_index()
alarm_count.columns = ['IdAlarm','Count']
#alarm_count.sort_values(by = "Count", ascending = False)
elif word == 'zone':
alarm_count = df[df.Description.str.contains(word)].IdAlarm.value_counts().reset_index()
alarm_count.columns = ['IdAlarm','Count']
#alarm_count.sort_values(by = "Count", ascending = False)
push_notebook()
show(bar_chart_interactive, notebook_handle=True)
# interaction
ipywidgets.interact(filter, word=drop_down)
到目前为止,我无法绘制过滤后的图表,然后,我无法更新绘制的图表。 有什么建议吗?
编辑:
我的 df 示例:
为此,您需要在一个单元格中运行 ipywidget,然后捕获值。在下一个单元格中,您可以根据选择将过滤器应用于 df 并进行绘图。 使用观察来捕获小部件选择值。 使用全局或自变量来存储值。
#first cell
drop_down = ipywidgets.Dropdown(options=['emergency',
'zone'],
description='Keyword:'
)
def observe_type_value(type_value):
global type_selection
type_selection = type_value['new']
print(type_selection)
drop_down.observe(observe_type_value, 'value')
display(drop_down)
#second cell
filter(type_selection)
#现在 df 已被过滤。使用此 df 进行绘图