Introduction to Streamlit
What is Streamlit?
Streamlit is an open-source Python library that
makes it easy to create and share beautiful, custom
web apps for machine learning and data science.
Why Streamlit?
• Turn data scripts into shareable web apps in
minutes
• All in pure Python - no front-end experience
required
• Instant deployment for sharing "The fastest way to build and share data apps"
• Widgets and interactivity with minimal code
Perfect for: Data scientists, ML engineers, analysts,
Created in 2019 and has quickly become one of the and anyone who wants to quickly create interactive
most popular tools for data scientists to share their data applications without web development
work. expertise.
Getting Started with Streamlit
Installation Your First Streamlit App
$ pip install streamlit import streamlit as st
# Title for your app
Running Your App
[Link]("My First Streamlit App")
$ streamlit run [Link]
# Add some text
Local URL: [Link]
[Link]("Hello, Streamlit!")
Key Concepts # Add a slider widget
x = [Link]("Select a value", 0, 100, 50)
• Scripts run from top to bottom
• Widget interaction reruns the script # Display the result
[Link](f"You selected: {x}")
• Hot-reloading: changes update live
Core Streamlit Widgets
Input Widgets Widget Example
Streamlit provides a variety of widgets to collect user import streamlit as st
input and create interactive applications.
# Text input
st.text_input() [Link]() name = st.text_input("Your name", "Type
Single-line text entry Clickable button here...")
[Link]() [Link]() # Slider
Numeric slider control Boolean checkbox age = [Link]("Your age", 0, 100, 25)
# Checkbox
[Link]() [Link]()
agree = [Link]("I agree")
Dropdown selection Radio button group
# Select box
option = [Link](
"How would you like to be contacted?",
("Email", "Phone", "Mail")
)
# Button
if [Link]("Submit"):
[Link](f"Hello {name}, you're {age} years
old")
Widget States
Important: Widgets maintain their state between
reruns. When a widget's value changes, the entire script
reruns with the new value.
Displaying Data in Streamlit
[Link]() [Link]()
Interactive dataframes with sorting and filtering Display JSON data in an interactive, collapsible format.
capabilities.
# Sample JSON data
import streamlit as st data = {
import pandas as pd 'name': 'Project',
'version': '1.0',
# Create sample dataframe 'settings': {
df = [Link]({ 'debug': True,
'Name': ['John', 'Mary', 'Bob'], 'theme': 'dark'
'Age': [25, 30, 35], }
'City': ['New York', 'Boston', 'Chicago'] }
})
# Display JSON
# Display interactive dataframe [Link](data)
[Link](df)
Data Display Comparison
[Link]()
Function Best For
Static tables for displaying data without interactivity.
[Link]() Interactive exploration of data
# Display static table
[Link]() Static display of small datasets
[Link](df)
[Link]() Displaying nested data structures
Layout and Media
Layout Options Media Elements
[Link] - Add widgets to a sidebar [Link] - Display images
import streamlit as st import streamlit as st
from PIL import Image
# Add widgets to sidebar
[Link]("Sidebar") # Display an image
option = [Link]( image = [Link]('[Link]')
"Choose a dataset:", [Link](image, caption='Sunset')
["Iris", "Penguins", "Wine"]
)
[Link] / [Link] - Embed media
[Link] - Create multiple columns
# Display audio
[Link]('audio.mp3')
# Create three columns
col1, col2, col3 = [Link](3) # Display video
[Link]('video.mp4')
# Add content to each column
[Link]("Temperature", "70 °F", "1.2 °F")
[Link]("Wind", "9 mph", "-8%")
[Link] - Collapsible sections
[Link]("Humidity", "86%", "4%")
with [Link]("See explanation"):
[Link]("This is hidden by default")
Advanced Streamlit Features
Caching for Performance Forms
Use @st.cache_data and @st.cache_resource Group related widgets that should be submitted together
decorators to avoid recomputation when your app using [Link] and st.form_submit_button.
reruns.
Custom Components
import streamlit as st
Extend Streamlit with custom React-based components for
import pandas as pd
specialized UI needs.
# This function will only run once
@st.cache_data Theming
def load_data():
Customize your app's look and feel with
return pd.read_csv("large_file.csv")
.streamlit/[Link] theme settings.
# Data loads instantly after first run
data = load_data() Callbacks
Use on_change, on_click, and on_value_change
Session State parameters to trigger functions when widget values
change.
Use st.session_state to preserve values between reruns.
# Initialize counter in session state
Secrets Management
if 'count' not in st.session_state: Store sensitive information securely using
st.session_state.count = 0 .streamlit/[Link] and access via [Link].
# Increment counter on button click
if [Link]("Increment"):
st.session_state.count += 1
# Display the count
[Link](f"Count: {st.session_state.count}")
Building a Simple Streamlit App
Data Visualization App
Let's build a simple data visualization app that allows
users to upload a CSV file and explore the data.
import streamlit as st
import pandas as pd
import [Link] as plt
# Title and file uploader
[Link]("Data Explorer")
uploaded_file = st.file_uploader("Upload
CSV")
if uploaded_file is not None:
# Read and display data
df = pd.read_csv(uploaded_file)
[Link]([Link]())
Key Components
# Column selection • File uploader for data input
column = [Link]("Select column", • Dataframe display to show the data
[Link])
• Selectbox for user interaction
# Create chart • Matplotlib integration for visualization
fig, ax = [Link]()
[Link](df[column])
This simple app demonstrates how quickly you can
[Link](fig) create interactive data tools with Streamlit.
Project: Data Dashboard
Sales Dashboard Project Dashboard Code
Let's build a sales dashboard with Streamlit: import streamlit as st
import pandas as pd
• Data upload and filters
import [Link] as px
• Key performance indicators
[Link]("Sales Dashboard")
• Interactive visualizations
# File uploader
# Project files
uploaded_file = st.file_uploader("Upload CSV")
sales_dashboard.py
if uploaded_file is None:
[Link]
df = pd.read_csv("sample_data.csv")
sample_data.csv
Deploying Streamlit Apps
Streamlit Cloud Other Deployment Options
The easiest way to deploy Streamlit apps is through
Heroku AWS
Streamlit Cloud, which offers free hosting for public
PaaS platform with free and Flexible cloud infrastructure
repositories. paid tiers
Deployment Steps
Google Cloud Run Docker
• Push your app to a GitHub repository Serverless container platform Containerized deployment
• Sign in to [Link]/cloud
Requirements File
• Connect your GitHub account
• Select repository and main file # [Link]
streamlit==1.24.0
pandas==1.5.3
matplotlib==3.7.1
Resources and Next Steps
Official Resources Next Steps
• Documentation: [Link]/docs
Build Your Portfolio Explore Components
• Gallery: [Link]/gallery Create and deploy your own Try out custom components
Streamlit apps to showcase to extend functionality
• Community: [Link] your skills
• GitHub: [Link]/streamlit/streamlit
Join Hackathons Contribute
Learning Resources Participate in Streamlit's Help improve Streamlit by
community challenges contributing to open source
• Streamlit Cheat Sheet - Quick reference guide
• 30 Days of Streamlit - Month-long tutorial series Contact
• YouTube Tutorials - Video walkthroughs For questions about this presentation or to learn more
about building with Streamlit, please contact:
Email: instructor@[Link]
GitHub: [Link]/instructor