twelsh37

Pandas Dataframe and ipywidgets dropdown

Nov 29th, 2020 (edited)
1,242
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import pandas as pd
  2. import numpy as np
  3. import ipywidgets as widgets
  4. from ipywidgets import Layout, AppLayout
  5. from IPython.display import display
  6. import functools
  7.  
  8.  
  9. # Initially, we will get the data and load it into a dataframe:
  10. # Updated data frame to load in our test data
  11. data = {'year': ['2000', '2000','2000','2000','2001','2001','2001','2001', '2002',  '2002', '2002', '2002',
  12.                  '2003','2003','2003','2003','2004', '2004','2004','2004', '2005', '2005', '2005', '2005',
  13.                  '2006', '2006', '2006', '2006', '2006', '2007', '2007', '2007', '2007', '2008', '2008', '2008', '2008',
  14.                  '2009', '2009', '2009', '2009'],
  15.        
  16.         'purpose':['Holiday', 'Business', 'VFR', 'Study', 'Holiday', 'Business', 'VFR', 'Study', 'Holiday', 'Business',
  17.                    'VFR', 'Study', 'Holiday', 'Business', 'VFR', 'Study', 'Holiday', 'Business', 'VFR', 'Study', 'Holiday',
  18.                    'Business', 'VFR', 'Study', 'Holiday', 'Business', 'VFR', 'Study', 'Holiday', 'Business', 'VFR', 'Study',
  19.                    'Holiday', 'Business', 'VFR', 'Study', 'Holiday', 'Business', 'VFR', 'Study', 'Holiday'
  20.                   ],
  21.        
  22.         'market':['Belgium', 'Luxembourg', 'France', 'Spain', 'Norway', 'Sweden', 'Germany', 'Austria', 'Denmark',
  23.                   'Portugal', 'Greece', 'Croatia', 'Belgium', 'Luxembourg', 'France', 'Spain', 'Norway', 'Sweden',
  24.                   'Germany', 'Austria', 'Denmark', 'Portugal', 'Greece', 'Croatia', 'Belgium', 'Luxembourg', 'France',
  25.                   'Spain', 'Norway', 'Sweden', 'Germany', 'Austria', 'Denmark', 'Portugal', 'Greece', 'Croatia', 'Belgium',
  26.                   'Luxembourg', 'France', 'Spain', 'Norway'
  27.                  ]}
  28.  
  29. df_london = pd.DataFrame (data, columns = ['year','purpose', 'market'])
  30.  
  31. #df_london = pd.read_csv(file, encoding = 'ISO-8859-1')
  32.  
  33. # Example of when the dropdown year is selected a new text box is
  34. # displayed to show the purpose filter
  35.  
  36. # Setup our List boxes to filter results based on filter choices
  37. ALL = 'ALL'
  38. def unique_sorted_values_plus_ALL(array):
  39.     unique = array.unique().tolist()
  40.     unique.sort()
  41.     unique.insert(0, ALL)
  42.     return unique
  43.  
  44. # variable to store the common output for the dropdowns
  45. output = widgets.Output()
  46.  
  47. # Here are the three dropdowns:
  48. dropdown_year = widgets.Dropdown(description='Year',
  49.                                   options = unique_sorted_values_plus_ALL(df_london.year))
  50.  
  51. dropdown_purpose = widgets.Dropdown(description='Purpose',
  52.                                      options = unique_sorted_values_plus_ALL(df_london.purpose))
  53.  
  54. dropdown_market = widgets.Dropdown(description='Market',
  55.                                     options = unique_sorted_values_plus_ALL(df_london.market))
  56.  
  57. # Function to filter our dropdown listboxes
  58. def common_filtering(year,purpose, market):
  59.    
  60.     # Make a copy of our data frame
  61.     df = df_london.copy()
  62.    
  63.     # Initialise our empty list
  64.     filters = []
  65.    
  66.     # Evaluate our dropdown list boxes and return booleans for our selections
  67.     if year is not ALL:
  68.         filters.append(df['year'] == year)
  69.     if purpose is not ALL:
  70.         filters.append(df['purpose'] == purpose)
  71.     if market is not ALL:
  72.         filters.append(df['market'] == market)
  73.    
  74.     # Ensure that we dont append our results to the cell
  75.     # but overwrite the old results with the new
  76.     output.clear_output()
  77.    
  78.    
  79.     with output:
  80.         if filters:
  81.             # Create a pandas Array of True/False for each of teh entries
  82.             df_filter = functools.reduce(lambda x,y: x&y, filters)
  83.             # Using dataframe.loc show our filtered results
  84.             display(df.loc[df_filter])
  85.         else:
  86.             # Otherwise display everything
  87.             display(df)
  88.  
  89. # We amend the event handlers to call the common_filtering function and pass the change.new value as well as the
  90. # current value of the other dropdown:    
  91.  
  92. def dropdown_year_eventhandler(change):
  93.     common_filtering(change.new, dropdown_purpose.value, dropdown_market.value)
  94.  
  95. def dropdown_purpose_eventhandler(change):
  96.     common_filtering(dropdown_year.value, change.new, dropdown_market.value,)
  97.    
  98. def dropdown_market_eventhandler(change):
  99.     common_filtering(dropdown_year.value, dropdown_purpose.value, change.new)
  100.  
  101. # We bind the handlers to the dropdowns, and that’s it!    
  102. dropdown_year.observe(dropdown_year_eventhandler, names='value')
  103. dropdown_purpose.observe(dropdown_purpose_eventhandler, names='value')
  104. dropdown_market.observe(dropdown_market_eventhandler, names='value')
  105.  
  106. # Setup our Hbox to display the list boxes in a line
  107. box_layout = widgets.Layout(display = 'inline-flex',
  108.                            flex_flow = 'row',
  109.                            align_items = 'stretch',
  110.                            border = 'solid',
  111.                            width = '100%')
  112. # Wrap up our widgets in a variable and assign them the box_layout style
  113. ui = widgets.HBox([dropdown_year, dropdown_purpose, dropdown_market], layout=box_layout)
  114.  
  115. # Display our dropdown boxes and the output from the selection
  116. display(ui, output)
  117.  
RAW Paste Data