Filter logic

Hi everyone, I currently have a view with a dataframe and 5 filters. The problem I have is that I can’t find a way to build a dynamic logic (users have the possibility to only use only 1 filter), and the only way I found is with the ‘if elif’ statement for all the combinations possible (not very convenient).

If there a better way to solve this?

Thanks!

Pierre

1 Like

Hi pvtaisne,

See below for an example with multiple filters for one dataframe. Let me know if it helps you :slight_smile:

import streamlit as st
import pandas as pd
import numpy as np

np.random.seed(0)  # Seed so random arrays do not change on each rerun
n_rows = 1000
random_data = pd.DataFrame(
    {"A": np.random.random(size=n_rows), "B": np.random.random(size=n_rows)}
)

sliders = {
    "A": st.sidebar.slider(
        "Filter A", min_value=0.0, max_value=1.0, value=(0.0, 1.0), step=0.01
    ),
    "B": st.sidebar.slider(
        "Filter B", min_value=0.0, max_value=1.0, value=(0.0, 1.0), step=0.01
    ),
}

filter = np.full(n_rows, True)  # Initialize filter as only True

for feature_name, slider in sliders.items():
    # Here we update the filter to take into account the value of each slider
    filter = (
        filter
        & (random_data[feature_name] >= slider[0])
        & (random_data[feature_name] <= slider[1])
    )

st.write(random_data[filter])
3 Likes

Thanks Peter, that is what I was looking for :slight_smile:

1 Like

Hey Peter,

Thank you for that reply, I was looking for something like that as well.

But could you explain what do you mean by “Initialize filter as onyl true”. I didn’t understand the purpose of this line: filter = np.full(n_rows, True) # Initialize filter as only True

Thanks again!

Hi Mariana,

The way the filtering works is that rows which are filtered away are set to false in the filter, and rows which are kept set to true. I initialize the filter to all true which corresponds to “no filter” and then apply filterings one at a time in the for loop. Hope it makes sense…

Best,
Peter

@PeterT, you are my saviour. Thanks for this useful tip. I’ve been looking for this solution for weeks. I have seen people asking for help on this issue on StackOverflow and Streamlit and the posts were left unanswered!