Filter dataframe by selections made in select box

Hi @srog,

Welcome to the Streamlit Community! You can definitely filter user inputs based on the selections in the select boxes you are using. This is not actually Streamlit functionality but Pandas functionality. For example, you could use:

df.loc[(df['make']=make_choice) & (df['year']=year_choice) & (df['model']= model_choice) & (df[engine]=engine_choice)]

This will display the pandas data frame with all of the user conditions met. However, it will not filter your further choices by the years of that make etc… You can do this by changing the order in how you’re creating your options for your dropdown selections.

import streamlit as st
import pandas as pd

@st.cache
def get_data():
path = r'cars.csv'
return pd.read_csv(path)
df = get_data()

makes = df['make'].drop_duplicates()
make_choice = st.sidebar.selectbox('Select your vehicle:', makes)
years = df["year"].loc[df["make"] = make_choice]
year_choice = st.sidebar.selectbox('', years) 
etc .... 

You can continue this pattern with the other two or filter them based on what the make of the car, like in this example.

In terms of the optimizing the loading of this data, I think it is fine the way you have it. This way a person who changes their choice in a β€œmake” of a car will not have to wait for a whole new data set to load. They just wait for pandas to filter their results (this is very fast).

Hope this helps!
Happy Streamlit-ing!
Marisa

5 Likes