先准备3个100%免费无门槛的工具和素材:
如果想快速上手,直接下载现成1000条202X年1-3月的模拟电商数据:https://pan.baidu.com/s/1Ww9vB8x9v7NkKQJZ3L1XwA 提取码:8888
如果想生成定制化数据(比如调整订单量、品类),新建名为generate_data.py的文件,粘贴以下完整代码,保存后双击运行: ``` import pandas as pd import numpy as np from faker import Faker from datetime import datetime, timedelta 初始化 fake = Faker(locale='zh_CN') np.random.seed(42) 固定随机数,方便复现 start_date = datetime(2024, 1, 1) end_date = datetime(2024, 3, 31) categories = ['服装', '电子产品', '食品', '家居', '美妆'] products = { '服装': ['T恤', '牛仔裤', '连衣裙', '羽绒服'], '电子产品': ['手机壳', '蓝牙耳机', '充电宝', '平板支架'], '食品': ['饼干', '坚果', '咖啡', '牛奶'], '家居': ['收纳箱', '拖鞋', '台灯', '枕头'], '美妆': ['口红', '面膜', '洗面奶', '防晒霜'] } order_statuses = ['已付款', '已发货', '已签收', '已退款'] provinces = fake.provinces() 生成数据 data = [] for _ in range(1000): 订单时间 delta_days = np.random.randint(0, (end_date - start_date).days) order_date = start_date + timedelta(days=delta_days) 品类与商品 category = np.random.choice(categories) product = np.random.choice(products[category]) 数量与单价 quantity = np.random.randint(1, 6) if category == '电子产品': price = np.random.randint(50, 500) elif category == '服装' or category == '家居': price = np.random.randint(30, 300) elif category == '美妆': price = np.random.randint(20, 250) else: price = np.random.randint(5, 100) 状态与用户 status = np.random.choice(order_statuses, p=[0.55, 0.25, 0.15, 0.05]) user_province = np.random.choice(provinces) 计算有效金额 valid_amount = round(quantity price, 2) if status != '已退款' else 0 存入列表 data.append({ '订单编号': fake.uuid4(), '下单时间': order_date, '商品品类': category, '商品名称': product, '购买数量': quantity, '商品单价': round(price, 2), '订单金额': round(quantity price, 2), '有效金额': valid_amount, '订单状态': status, '用户省份': user_province }) 导出CSV df = pd.DataFrame(data) df.to_csv('mall_data.csv', index=False, encoding='utf-8-sig') utf-8-sig避免中文乱码 print(f"✅ 成功生成1000条数据,文件名为mall_data.csv") ```
运行完成后,会在当前文件夹生成mall_data.csv,这就是我们的数据源。

新建名为mall_dashboard.py的文件,粘贴以下完整可运行的Streamlit代码,保存后放在和mall_data.csv同一文件夹: ``` import streamlit as st import pandas as pd import plotly.express as px 设置页面基础配置 st.set_page_config(page_title="本地商城数据分析看板", page_icon="🛒", layout="wide") - 数据加载与预处理 - @st.cache_data 缓存数据,提高加载速度 def load_data(): df = pd.read_csv('mall_data.csv', encoding='utf-8-sig') df['下单时间'] = pd.to_datetime(df['下单时间']) df['下单月份'] = df['下单时间'].dt.to_period('M').astype(str) return df df = load_data() - 侧边栏筛选条件 - st.sidebar.header("🔍 筛选条件") 月份筛选 months = sorted(df['下单月份'].unique()) selected_months = st.sidebar.multiselect("选择月份", months, default=months) 品类筛选 categories = sorted(df['商品品类'].unique()) selected_categories = st.sidebar.multiselect("选择商品品类", categories, default=categories) 状态筛选 statuses = sorted(df['订单状态'].unique()) selected_statuses = st.sidebar.multiselect("选择订单状态", statuses, default=statuses) 省份筛选(可选前10热门省份) provinces_order = df.groupby('用户省份')['有效金额'].sum().sort_values(ascending=False).index.tolist() top10_provinces = provinces_order[:10] selected_provinces = st.sidebar.multiselect("选择用户省份", provinces_order, default=top10_provinces) 应用筛选 filtered_df = df[ (df['下单月份'].isin(selected_months)) & (df['商品品类'].isin(selected_categories)) & (df['订单状态'].isin(selected_statuses)) & (df['用户省份'].isin(selected_provinces)) ] - 核心指标卡片 - st.title("🛒 本地商城数据分析看板") st.divider() col1, col2, col3, col4 = st.columns(4) with col1: total_sales = filtered_df['有效金额'].sum() st.metric(label="总有效销售额", value=f"¥{total_sales:,.2f}") with col2: total_orders = filtered_df.shape[0] st.metric(label="总订单数", value=f"{total_orders:,}") with col3: avg_order_amount = filtered_df['有效金额'].mean() if total_orders > 0 else 0 st.metric(label="客单价", value=f"¥{avg_order_amount:,.2f}") with col4: refund_rate = (filtered_df['订单状态'] == '已退款').sum() / total_orders 100 if total_orders > 0 else 0 st.metric(label="退款率", value=f"{refund_rate:.2f}%") - 图表区域 - st.divider() col_left, col_right = st.columns(2) 左列:月度有效销售额趋势 with col_left: st.subheader("📈 月度有效销售额趋势") monthly_sales = filtered_df.groupby('下单月份')['有效金额'].sum().reset_index() fig_monthly = px.line(monthly_sales, x='下单月份', y='有效金额', markers=True, title='', text='有效金额') fig_monthly.update_traces(textposition='top center', texttemplate='¥%{text:,.0f}') fig_monthly.update_layout(yaxis_title="有效销售额(元)", xaxis_title="", margin=dict(l=0, r=0, t=20, b=0)) st.plotly_chart(fig_monthly, use_container_width=True) 右列:品类销售占比 with col_right: st.subheader("🥧 商品品类销售占比") category_sales = filtered_df.groupby('商品品类')['有效金额'].sum().reset_index().sort_values(by='有效金额', ascending=False) fig_category = px.pie(category_sales, values='有效金额', names='商品品类', hole=0.3, title='') fig_category.update_traces(textposition='inside', texttemplate='%{percent:.1%}') fig_category.update_layout(margin=dict(l=0, r=0, t=20, b=0)) st.plotly_chart(fig_category, use_container_width=True) 下一行:省份有效销售额TOP10 + 商品热销TOP5 col_bottom_left, col_bottom_right = st.columns(2) with col_bottom_left: st.subheader("🏆 省份有效销售额TOP10") province_sales = filtered_df.groupby('用户省份')['有效金额'].sum().reset_index().sort_values(by='有效金额', ascending=False).head(10) fig_province = px.bar(province_sales, x='有效金额', y='用户省份', orientation='h', text='有效金额') fig_province.update_traces(textposition='outside', texttemplate='¥%{text:,.0f}') fig_province.update_layout(yaxis_title="", xaxis_title="有效销售额(元)", yaxis={'categoryorder':'total ascending'}, margin=dict(l=0, r=0, t=20, b=0)) st.plotly_chart(fig_province, use_container_width=True) with col_bottom_right: st.subheader("🔥 商品热销TOP5") product_sales = filtered_df.groupby('商品名称')['购买数量'].sum().reset_index().sort_values(by='购买数量', ascending=False).head(5) fig_product = px.bar(product_sales, x='商品名称', y='购买数量', text='购买数量') fig_product.update_traces(textposition='outside') fig_product.update_layout(yaxis_title="购买数量", xaxis_title="", margin=dict(l=0, r=0, t=20, b=0)) st.plotly_chart(fig_product, use_container_width=True) - 原始数据展示 - st.divider() st.subheader("📋 筛选后的原始订单数据") 分页展示,每页20条 page_size = 20 total_pages = (filtered_df.shape[0] + page_size - 1) // page_size page_number = st.number_input("页码", min_value=1, max_value=total_pages, value=1) start_idx = (page_number - 1) page_size end_idx = start_idx + page_size st.dataframe(filtered_df.iloc[start_idx:end_idx], use_container_width=True) ```
打开终端(必须进入存放两个文件的文件夹!卡壳请按以下步骤):
在打开的终端中复制以下命令并回车: ``` streamlit run mall_dashboard.py ```
终端会自动打开浏览器显示看板,若未自动打开,复制终端显示的Local URL(通常是http://localhost:8501)手动粘贴到浏览器即可。
使用方式:左侧侧边栏调整筛选条件,所有核心指标和图表会实时更新,底部还能查看原始订单的分页数据。
易频IT社区是综合性互联网IT技术门户网站,专注分享网络技术、服务器运维、网络安全、编程开发、系统架构、云计算、大数据等行业干货,实时更新IT行业资讯、零基础教程、实战案例,为IT从业者、技术爱好者提供专业的学习交流平台。
Copyright © 2021-2026 易频IT社区. All Rights Reserved. 备案号:闽ICP备2023013482号 网站地图