在python中使用下拉菜单和字符串过滤字符串

cnjp1d6j  于 11个月前  发布在  Python
关注(0)|答案(1)|浏览(356)

我有一个由八列组成的df。我对其中的两列感兴趣:“Id”和“Description”。“Id”包含数值,而“Description”包含字符串值(例如“高紧急”、“低紧急”、“区域1”)。我想使用包含选定单词列表的下拉菜单来过滤df。例如,在下拉菜单中选择单词“emergency”,结果应该是仅用列“Description”中包含单词“emergency”的行过滤的新DF。
一旦过滤了这个,我想在一个条形图中绘制剩余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示例:
sample df

7rfyedvj

7rfyedvj1#

为此,您需要在一个单元格中运行ipywidget,然后捕获值。在下一个单元格中,您可以根据选择将过滤器应用于df并进行绘图。使用observe捕获widget选择值。使用global或self变量存储值。

#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进行绘图

相关问题