一、Streamlit 基础核心
1.1 核心特性与安装
Streamlit 是专为数据科学打造的 Python Web 框架,具备以下特性:
- 实时热重载:修改代码后自动刷新浏览器
- 零前端开发经验要求
- 原生集成主流数据可视化库
- 内置会话状态管理
安装命令:
pip install streamlit==1.34.0 pandas==2.2.2 plotly==5.18.0
1.2 基础组件详解
文本显示
import streamlit as st
st.title("销售分析看板") # 顶层标题,自动居中
st.header("区域销售趋势") # 次级标题
st.subheader("2024年Q1数据") # 三级标题
st.markdown("**重点指标**: 红色表示异常值") # 支持Markdown语法
st.write("自动类型推导显示:", [1, 2, 3], {
"key": "value"}) # 万能输出方法
数据展示
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 5), columns=('产品A', '产品B', '产品C', '产品D', '产品E'))
st.dataframe(df.style.highlight_max(axis=0)) # 交互式表格,支持排序
st.table(df.iloc[0:5]) # 静态表格,完整渲染HTML
st.metric(label="当前温度", value="23℃", delta="-1.2℃") # 指标卡
可视化组件
chart_data = pd.DataFrame(np.random.randn(20, 3), columns=['a', 'b', 'c'])
# 原生图表
st.line_chart(chart_data, y=['a', 'b'], height=300)
# Matplotlib集成
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.scatter(chart_data['a'], chart_data['b'])
st.pyplot(fig)
# Plotly高级图表
import plotly.express as px
fig = px.scatter_3d(chart_data, x='a', y='b', z='c')
st.plotly_chart(fig, use_container_width=True)
交互组件
# 输入类组件
name = st.text_input("请输入姓名", max_chars=20)
age = st.number_input("年龄", min_value=0, max_value=150, step=1)
colors = st.multiselect("选择颜色", ['红', '蓝', '绿'], default=['红'])
# 按钮类组件
if st.button("开始分析", type="primary"):
st.toast('分析进行中...', icon='⏳')
# 表单批量提交
with st.form("user_info"):
email = st.text_input("邮箱")
submitted = st.form_submit_button("提交")
if submitted:
validate_email(email)
二、高级开发技巧
2.1 界面布局优化
# 多列布局
col1, col2, col3 = st.columns([2, 1, 1])
with col1:
st.map(df) # 占据2/4宽度
with col2:
st.metric("UV", "1.2万")
with col3:
st.metric("PV", "8.9万")
# 选项卡布局
tab1, tab2 = st.tabs(["原始数据", "统计分析"])
with tab1:
st.dataframe(df)
with tab2:
st.line_chart(df.describe().T[['mean', '50%']])
# 扩展器组件
with st.expander("点击查看详细说明"):
st.markdown("""
## 数据来源说明
1. 销售数据来自ERP系统
2. 用户数据来自GA平台
""")
2.2 性能优化缓存
@st.cache_data(ttl=3600) # 缓存数据计算结果
def process_large_data(file):
# 模拟耗时操作
time.sleep(3)
return pd.read_csv(file).dropna()
@st.cache_resource # 缓存资源型对象
def get_ml_model():
return load_pretrained_model('model.pkl')
uploaded_file = st.file_uploader("上传数据文件")
if uploaded_file:
processed_data = process_large_data(uploaded_file)
model = get_ml_model()
2.3 状态管理进阶
# 初始化会话状态
if 'click_count' not in st.session_state:
st.session_state.click_count = 0
# 状态更新回调函数
def increment_counter():
st.session_state.click_count += 1
st.button("点击计数", on_click=increment_counter)
st.write(f"当前计数: {
st.session_state.click_count}")
# 跨页面状态保持
st.session_state.update({
'filter_params': {
'start_date': '2024-01-01',
'end_date': '2024-03-31'
}
})
2.4 文件处理实战
uploaded_files = st.file_uploader(
"上传Excel文件",
type=['xlsx', 'xls'],
accept_multiple_files=True
)
if uploaded_files:
dfs = []
for file in uploaded_files:
dfs.append(pd.read_excel(file))
combined_df = pd.concat(dfs)
st.download_button(
label="下载合并数据",
data=combined_df.to_csv().encode('utf-8'),
file_name='combined_data.csv',
mime='text/csv'
)
三、完整报表系统实现
# 报表系统完整代码
import streamlit as st
import pandas as pd
import plotly.express as px
from io import BytesIO
# 初始化页面配置
st.set_page_config(
page_title="智能业务分析系统",
layout="wide",
initial_sidebar_state="expanded"
)
# 数据加载模块
@st.cache_data
def load_data(uploaded_file):
try:
return pd.read_excel(uploaded_file)
except Exception as e:
st.error(f"文件读取失败: {
str(e)}")
return None
# 主界面
def main():
# 侧边栏配置
with st.sidebar:
st.header("数据上传")
uploaded_file = st.file_uploader(
"选择Excel文件",
type=['xlsx'],
help="支持XLSX格式,最大文件大小200MB"