New Component: Dynamic multi-select filters

Hi All! :balloon: I built a new (and my first) component. It’s a fairly simple wrapper for st.multiselect' which uses st.session_state and st.experimental_rerun under the hood to show only relevant values in filter options and dynamically filter a dataframe (similar to Google Sheets slicers or Only Relevant Values in Tableau behaviour).

Check out the demo app here - Dynamic Filters Demo App

How to install and use the package:

  1. Install the package using pip:
    pip install streamlit-dynamic-filters

  2. Import the DynamicFilters class:
    from streamlit_dynamic_filters import DynamicFilters

  3. Create an instance of the DynamicFilters class and pass the dataframe and the list of fields that will serve as filters:

    dynamic_filters = DynamicFilters(df, filters=['col1', 'col2', 'col3', 'col4'])

  4. Display the filters in your app:
    dynamic_filters.display_filters()

  5. Display the filtered dataframe:
    dynamic_filters.display_df()

Demo GIF:

Sample usage:

import streamlit as st
from streamlit_dynamic_filters import DynamicFilters

data = {
    'Region': ['North America', 'North America', 'North America', 'Europe', 'Europe', 'Asia', 'Asia'],
    'Country': ['USA', 'USA', 'Canada', 'Germany', 'France', 'Japan', 'China'],
    'City': ['New York', 'Los Angeles', 'Toronto', 'Berlin', 'Paris', 'Tokyo', 'Beijing']
    }

df = pd.DataFrame(data)

dynamic_filters = DynamicFilters(df, filters=['Region', 'Country', 'City'])

with st.sidebar:
    dynamic_filters.display_filters()

dynamic_filters.display_df()

Any feedback is much appreciated :innocent: Hopefully, it’ll be useful for someone, personally I’ve been struggling with if/else logic to make the filters dynamic and our users had to only apply them from top to bottom, so being able to use session state is a game changer for me.

9 Likes

What an awesome idea and component! :heart_eyes:

This is a really great feature, Thanks for bringing this up! I wanted to ask if there’s any way to align these filters using st.columns?

@Rajat_Choudhary great question. I don’t think there is an option for this with the current setup. I’ll see if I can update the component to allow more flexibility

Hi @Oleksandr_Arsentiev , another question I had. Can we save this filtered dataframe that’s displayed using display_df() into a new dataframe as I might use it for further drill down, Thanks

You should be able to get that using dynamic_filters.filter_except(). This seems to be undocumented API so you are on your own.

1 Like

Is there a way to set default values in the multip-select box. Thanks

Thanks @Goyo

Take a look at the default argument to multiselect