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

cnjp1d6j  于 2024-01-10  发布在  Python
关注(0)|答案(1)|浏览(449)

我有一个由八列组成的df。我对其中的两列感兴趣:“Id”和“Description”。“Id”包含数值,而“Description”包含字符串值(例如“高紧急”、“低紧急”、“区域1”)。我想使用包含选定单词列表的下拉菜单来过滤df。例如,在下拉菜单中选择单词“emergency”,结果应该是仅用列“Description”中包含单词“emergency”的行过滤的新DF。
一旦过滤了这个,我想在一个条形图中绘制剩余Id的出现次数(用value_counts()方法计数),该条形图根据下拉菜单中所选的关键字进行更新。
我在这里报告我到现在为止写的代码(df已经导入):

  1. import ipywidgets
  2. from bokeh.io import push_notebook
  3. from bokeh.plotting import figure
  4. from bokeh.io import output_notebook, show, reset_output
  5. from bokeh.models import Range1d
  6. output_notebook()
  7. # drop-down widget
  8. drop_down = ipywidgets.Dropdown(options=['emergency',
  9. 'zone'],
  10. description='Keyword:'
  11. )
  12. #data. I have problems here because I am passing alarm_count that is defined later in the function
  13. x_bar_data_ipyw = alarm_count.IdAlarm.astype(str)
  14. y_bar_data_ipyw = alarm_count.Count
  15. # figure and plot
  16. bar_chart_interactive = figure(x_range=x_bar_data_ipyw, plot_height=300)
  17. bar_ipyw = bar_chart_interactive.vbar(x_bar_data_ipyw, top=y_bar_data_ipyw, color='green', width=0.5)
  18. bar_chart_interactive.y_range=Range1d(0, 18)
  19. # function - bar chart
  20. def filter(word):
  21. if word == 'emergency':
  22. alarm_count = []
  23. alarm_count = df[df.Description.str.contains(word)].IdAlarm.value_counts().reset_index()
  24. alarm_count.columns = ['IdAlarm','Count']
  25. #alarm_count.sort_values(by = "Count", ascending = False)
  26. elif word == 'zone':
  27. alarm_count = df[df.Description.str.contains(word)].IdAlarm.value_counts().reset_index()
  28. alarm_count.columns = ['IdAlarm','Count']
  29. #alarm_count.sort_values(by = "Count", ascending = False)
  30. push_notebook()
  31. show(bar_chart_interactive, notebook_handle=True)
  32. # interaction
  33. ipywidgets.interact(filter, word=drop_down)

字符串
到目前为止,我无法绘制过滤后的图形,然后,我无法更新绘制的图形。有什么建议吗?
编辑:
我的DF示例:
sample df

7rfyedvj

7rfyedvj1#

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

  1. #first cell
  2. drop_down = ipywidgets.Dropdown(options=['emergency',
  3. 'zone'],
  4. description='Keyword:'
  5. )
  6. def observe_type_value(type_value):
  7. global type_selection
  8. type_selection = type_value['new']
  9. print(type_selection)
  10. drop_down.observe(observe_type_value, 'value')
  11. display(drop_down)
  12. #second cell
  13. filter(type_selection)

字符串

现在df已过滤。使用此df进行绘图

展开查看全部

相关问题