Show the entire DataFrame if any filter is selected in streamlit

Question:

I want streamlit to show the entire DataFrame when any filters are applied.

Here is the code I think will be useful enough:

df = pd.read_csv('classes_particulars.csv')

#Filters
idCode = st.sidebar.multiselect(
    "Selecciona un ID",
    ('ABSUDUHM', 'DWHWBMMX', 'MIXEECJR', 'NFKQWKOP', 'RQWLPVCJ')
)
preuPagat = st.sidebar.number_input(
    "Preu pagat"
)

dfSelection = df.query(
    "Preu == @preuPagat or ID == @idCode"
)

To show the dfSelection I code:

st.table(dfSelection)

However, I want to display st.table(df) if no filters are selected.

Here is what I have tried with a bunch of errors:

if df.query("Preu == @preuPagat or ID == @idCode"):
    df.table(dfSelection)
else:
    df.table(df)

The error I got is this:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Here is how the streamlit app looks like when using st.table(df):
enter image description here

Here is how streamlit app looks like when using:

if len(df.query("Preu == @preuPagat or ID == @idCode")):
    st.table(dfSelection)
else:
    st.table(df

enter image description here
Any help on this?

Asked By: Adrià Martínez

||

Answers:

Use len(df) to check if something is filtered.
Also use st.table(df), and not df.table(df)

...

if len(df.query("Preu == @preuPagat or ID == @idCode")):
    st.table(dfSelection)
else:
    st.table(df)

Or

...

dfSelection = df.query(
    "Preu == @preuPagat or ID == @idCode"
)

if len(dfSelection):
    st.table(dfSelection)
else:
    st.table(df)

Full code

import streamlit as st
import pandas as pd

data= {
    'Preu':[14, 15, 14, 12, 15],
    'ID' :['ABSUDUHM','DWHWBMMX','MIXEECJR','NFKQWKOP','RQWLPVCJ']
}

# df = pd.read_csv('classes_particulars.csv')
st.header('Dashboard')
df = pd.DataFrame(data)

#Filters
idCode = st.sidebar.multiselect(
    "Selecciona un ID",
    ('ABSUDUHM', 'DWHWBMMX', 'MIXEECJR', 'NFKQWKOP', 'RQWLPVCJ')
)
preuPagat = st.sidebar.number_input(
    "Preu pagat"
)

dfSelection = df.query(
    "Preu == @preuPagat or ID == @idCode"
)

if len(dfSelection):
    st.table(dfSelection)
else:
    st.table(df)

Output

enter image description here

Answered By: ferdy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.