To create a Streamlit app with the functionalities you described, you can follow the code structure below. This code uses the Streamlit library to create a simple web application that allows the user to input a search term and filter a DataFrame based on that term.
First, make sure you have Streamlit installed in your Python environment. If not, you can install it using pip:
pip install streamlit
Once Streamlit is installed, you can write the following code in a Python script (e.g., app.py):
import streamlit as st
import pandas as pd
# Sample DataFrame
data = {
'A': ['foo', 'bar', 'baz', 'qux'],
'B': ['one', 'two', 'foo', 'three'],
'C': ['x', 'y', 'foo', 'z'],
}
df = pd.DataFrame(data)
# Start of Streamlit app
st.title('DataFrame Search App')
# Show the initial DataFrame
st.write('Initial DataFrame:')
st.dataframe(df)
# Get search_word as input from the user
search_word = st.text_input('Enter a search word:')
# Button to trigger the search
if st.button('Search'):
# When the button is pressed, find search_word in the whole df
filtered_df = df[df.apply(lambda row: row.astype(str).str.contains(search_word).any(), axis=1)]
# Show the filtered DataFrame as output
st.write('Filtered DataFrame:')
st.dataframe(filtered_df)
To run the Streamlit app, navigate to the folder containing your script in the terminal and execute the following command:
streamlit run app.py
Streamlit will start a local server and open your web browser to display the app. You'll see the initial DataFrame displayed, and you'll be able to input a search term. When you press the "Search" button, the app will show the filtered DataFrame based on your search term.
Remember, Streamlit’s interactivity is handled automatically, so you don't need to write explicit callbacks for widgets like you do with some other libraries.