【Python Streamlit库实战】轻松构建交互式Web应用程序指南
Streamlit 是一个开源的 Python 库,用于快速构建交互式 Web 应用程序,特别适合数据科学家和机器学习工程师。它以简单直观的 API 著称,允许用户通过纯 Python 代码创建数据可视化、仪表板和交互式工具,无需前端开发经验。Streamlit 应用程序可以通过浏览器访问,支持实时更新和用户交互,广泛用于数据探索、模型展示和快速原型开发。
以下是对 Streamlit 库的详细介绍,包括其功能、用法和实际应用。
1. Streamlit 库的作用
2. 安装与环境要求
pandas:数据处理。numpy:数值计算。tornado:Web 服务器。matplotlib、plotly)。pip install streamlit
streamlit hello
http://localhost:8501)。streamlit run app.py
app.py 是包含 Streamlit 代码的 Python 文件。3. 核心功能与用法
Streamlit 的核心是通过 st 模块提供的函数(如 st.write、st.button)构建应用界面。以下是主要功能和示例。
3.1 显示文本和数据
使用 st.write、st.title 等显示内容。
import streamlit as st
st.title("My First Streamlit App")
st.write("Welcome to Streamlit!")
st.markdown("This is **bold** text with *italics*.")
说明:
st.title:设置页面标题。st.write:通用输出,支持文本、数据框、图表等。st.markdown:渲染 Markdown 格式文本。3.2 交互控件
支持多种输入控件,实现用户交互。
import streamlit as st
# 文本输入
name = st.text_input("Enter your name", "John Doe")
st.write(f"Hello, {name}!")
# 滑块
age = st.slider("Select your age", min_value=0, max_value=100, value=25)
st.write(f"You are {age} years old.")
# 下拉菜单
option = st.selectbox("Choose a color", ["Red", "Blue", "Green"])
st.write(f"Selected color: {option}")
# 按钮
if st.button("Click me"):
st.write("Button clicked!")
说明:
name、age),可用于动态更新。3.3 数据可视化
集成 Pandas、Matplotlib、Plotly 等库展示数据。
import streamlit as st
import pandas as pd
import plotly.express as px
# 显示数据框
df = pd.DataFrame({
"x": [1, 2, 3, 4],
"y": [10, 20, 25, 30]
})
st.dataframe(df)
# 绘制图表
fig = px.line(df, x="x", y="y", title="Simple Line Chart")
st.plotly_chart(fig)
说明:
st.dataframe:显示交互式数据表。st.plotly_chart:渲染 Plotly 图表(支持 matplotlib、altair 等)。3.4 文件上传
处理用户上传的文件(如 CSV、图片)。
import streamlit as st
import pandas as pd
uploaded_file = st.file_uploader("Upload a CSV file", type=["csv"])
if uploaded_file is not None:
df = pd.read_csv(uploaded_file)
st.write("Uploaded Data:")
st.dataframe(df)
说明:
st.file_uploader:支持指定文件类型。3.5 缓存数据
使用 @st.cache_data 缓存昂贵计算,提高性能。
import streamlit as st
import pandas as pd
@st.cache_data
def load_data():
# 模拟昂贵操作
return pd.DataFrame({"col1": range(1000), "col2": range(1000, 2000)})
df = load_data()
st.write("Cached Data:", df.head())
说明:
@st.cache_data 缓存函数结果,避免重复计算。3.6 布局与容器
使用 st.columns、st.sidebar 组织界面。
import streamlit as st
# 侧边栏
st.sidebar.title("Settings")
option = st.sidebar.selectbox("Mode", ["Light", "Dark"])
# 列布局
col1, col2 = st.columns(2)
with col1:
st.write("Column 1 content")
with col2:
st.write("Column 2 content")
说明:
st.sidebar:将控件放入侧边栏。st.columns:创建多列布局。4. 性能与特点
streamlit.components 支持自定义 HTML/JavaScript。5. 实际应用场景
示例(交互式数据分析):
import streamlit as st
import pandas as pd
import plotly.express as px
st.title("Data Analysis Dashboard")
# 文件上传
uploaded_file = st.file_uploader("Upload CSV", type=["csv"])
if uploaded_file:
df = pd.read_csv(uploaded_file)
st.dataframe(df.head())
# 列选择
column = st.selectbox("Select column to plot", df.columns)
fig = px.histogram(df, x=column)
st.plotly_chart(fig)
# 过滤数据
threshold = st.slider("Filter threshold", float(df[column].min()), float(df[column].max()))
filtered_df = df[df[column] > threshold]
st.write("Filtered Data:", filtered_df)
说明:
6. 部署
Streamlit 应用可以本地运行或部署到云端。
streamlit run app.py
- 将代码推送到 GitHub 仓库。
- 登录 Streamlit Community Cloud(https://share.streamlit.io/)。
- 连接 GitHub 仓库,配置
app.py和requirements.txt。 - 部署后获取公共 URL。
FROM python:3.9
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["streamlit", "run", "app.py", "--server.port=8501"]
7. 注意事项
@st.cache_data 优化。st 函数。st.session_state)。if "count" not in st.session_state:
st.session_state.count = 0
if st.button("Increment"):
st.session_state.count += 1
st.write("Count:", st.session_state.count)
import os
api_key = os.getenv("API_KEY")
8. 综合示例
以下是一个综合示例,展示数据上传、可视化和交互过滤:
import streamlit as st
import pandas as pd
import plotly.express as px
st.title("Interactive Data Explorer")
# 侧边栏设置
st.sidebar.header("Options")
chart_type = st.sidebar.selectbox("Chart Type", ["Line", "Scatter", "Histogram"])
# 文件上传
uploaded_file = st.file_uploader("Upload a CSV file", type=["csv"])
if uploaded_file:
@st.cache_data
def load_data():
return pd.read_csv(uploaded_file)
df = load_data()
st.write("Data Preview:", df.head())
# 选择列
columns = df.columns.tolist()
x_col = st.selectbox("X-axis", columns)
y_col = st.selectbox("Y-axis", columns)
# 绘制图表
if chart_type == "Line":
fig = px.line(df, x=x_col, y=y_col)
elif chart_type == "Scatter":
fig = px.scatter(df, x=x_col, y=y_col)
else:
fig = px.histogram(df, x=x_col)
st.plotly_chart(fig)
# 数据过滤
if st.checkbox("Filter Data"):
threshold = st.slider(f"Filter {y_col} >", float(df[y_col].min()), float(df[y_col].max()))
filtered_df = df[df[y_col] > threshold]
st.write("Filtered Data:", filtered_df)
说明:
9. 资源与文档
作者:彬彬侠