Df.query() produces key error when passing key from selectbox

I am trying to populate a dropdown from the df.columns, streamlit is successful in this. After selecting a column, the next filter dropdown is populated by the unique properties of the selected column. And so on.

I am trying to pass the results of the query to df.query() but I haven’t managed to do that. It always returns a key error. Is there a pattern I can use to pass @key == @parameter in a way that will work?

CSV data is here:
https://files.catbox.moe/i544mb.zip

from fileinput import filename
import pandas as pd
import streamlit as st
import plotly.express as px



st.set_page_config(page_title="data-vis",
                    page_icon=":punch:",
                    layout="wide")

@st.cache
def get_data_from_csv():
    df = pd.read_csv(
        filepath_or_buffer="/filepath/to/downloaded.csv",
        low_memory=False,
    )
    return df

df = get_data_from_csv()



st.sidebar.header("Please filter here:")


filter_1 = st.sidebar.selectbox(
    "FILTER ONE", options=df.columns,
    index=1,
)

param_1 = st.sidebar.selectbox(
    "PARAM",
    options=df[filter_1].unique(),
)

def run_query():
    try:
        df_selection = df.query(
            '@filter_1 == @param_1'
        )
    except:
        df_selection = df
    return df_selection


def run_query2():
    df_selection = df[filter_1 == param_1]
    return df_selection

data_load_state = st.text('Loading data...')
st.dataframe(run_query())
data_load_state = st.text('Done!')

Hi @NomeChomsky, welcome to the Streamlit community!

For the pattern you are trying to achieve, you can use f-strings:


def run_query():
    try:
        df_selection = df.query(
            f'@{filter_1} == @{param_1}'
        )
    except:
        df_selection = df
    return df_selection

The code above is untested, but that’s effectively how you do the pattern you are talking about. Streamlit selectbox widget will return a string, and then you pass the string around wherever you need it using f-strings.

Best,
Randy

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.