import streamlit as st import pandas as pd import numpy as np # 设置matplotlib后端为Agg(非交互式后端),解决scheduling failure问题 import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import io import matplotlib.font_manager as fm import os # 注册思源黑体字体 font_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'SourceHanSansSC-Normal-2.otf') # 创建字体属性对象 chinese_font = fm.FontProperties(fname=font_path) # 设置全局字体属性 plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题 # 设置页面标题 st.title('价格段图表生成') st.markdown("上传卖家精灵下载的数据源,根据价格段生成对应的可视化图表和表格") # 添加示例文件按钮 st.link_button( "📊 数据源示例", "https://objects.mambate.top/example/价格段数据源示例.xlsx", help="点击下载数据源示例文件" ) st.link_button( "📈 下载结果示例", "https://objects.mambate.top/example/价格段图表结果.png", help="点击查看图表结果示例" ) st.divider() # 添加分隔线 # 上传文件功能 uploaded_file = st.file_uploader("上传商品数据Excel文件", type=['xlsx', 'csv']) if uploaded_file is not None: try: # 尝试读取Excel文件 df = pd.read_excel(uploaded_file) # 显示原始数据的前几行 st.subheader('原始数据预览') st.dataframe(df.head()) # 查找匹配的列名(只匹配开头部分) def find_column_by_prefix(df, prefix): for col in df.columns: if isinstance(col, str) and col.startswith(prefix): return col return None # 匹配列名 price_column = find_column_by_prefix(df, '价格') quantity_col = find_column_by_prefix(df, '月销量') sales_col = find_column_by_prefix(df, '月销售额') # 检查是否找到了所有必要的列 if not price_column: st.error('无法找到价格列,请确保您的数据包含以"价格"开头的列') elif not quantity_col: st.error('无法找到月销量列,请确保您的数据包含以"月销量"开头的列') elif not sales_col: st.error('无法找到月销售额列,请确保您的数据包含以"月销售额"开头的列') else: # 显示匹配到的列名 st.info(f'已匹配列: 价格列="{price_column}", 销量列="{quantity_col}", 销售额列="{sales_col}"') # 获取价格数据 prices = df[price_column].dropna() # 移除非数值数据 prices = pd.to_numeric(prices, errors='coerce').dropna() if len(prices) == 0: st.error('价格列不包含有效数值') else: # 获取最小和最大价格 min_price = prices.min() max_price = prices.max() # 向下取整最小价格 min_price_floor = np.floor(min_price) # 添加手动设置最大最小值的选项 use_custom_range = st.checkbox('手动设置价格区间范围', value=False) if use_custom_range: col1, col2 = st.columns(2) with col1: custom_min_price = st.number_input( '设置最小价格', min_value=0.0, value=float(min_price), step=1.0, format="%.2f" ) with col2: custom_max_price = st.number_input( '设置最大价格', min_value=float(custom_min_price), value=float(max_price), step=1.0, format="%.2f" ) # 使用自定义的最大最小值 min_price = custom_min_price max_price = custom_max_price # 用户输入区间大小 interval_size = st.number_input( f'输入价格区间大小 (最小价格: {min_price:.2f}, 最大价格: {max_price:.2f})', min_value=1, value=5, step=1 ) if st.button('生成价格区间分析'): # 计算区间起点(向下取整到interval_size的倍数) start_price = np.floor(min_price / interval_size) * interval_size # 创建区间 intervals = [] if use_custom_range: # 使用自定义范围时的特殊处理 current_price = start_price # 当手动设置范围时,确保从用户设置的最小值开始 # 覆盖start_price,直接使用custom_min_price作为起点 current_price = custom_min_price # 添加常规区间 while current_price < custom_max_price: next_price = current_price + interval_size # 如果下一个价格点超过了自定义最大值,则使用自定义最大值作为上限 if next_price > custom_max_price: next_price = custom_max_price intervals.append((current_price, next_price, f"{int(current_price) if current_price.is_integer() else current_price}-{int(next_price) if next_price.is_integer() else next_price}")) current_price = next_price # 添加"以上"区间 intervals.append((custom_max_price, float('inf'), f"{int(custom_max_price) if custom_max_price.is_integer() else custom_max_price}以上")) else: # 使用实际的最小价格作为起点,确保不会出现负数区间 if start_price < 0: start_price = 0 # 将start_price调整为最小价格的区间开始点(保持interval_size的整数倍数) # 如果最小价格比start_price大,则往下调整区间起点以包含最小价格 while start_price > min_price: start_price -= interval_size # 计算需要的区间数量 num_intervals = int(np.ceil((max_price - start_price) / interval_size)) + 1 # 创建常规区间 for i in range(num_intervals): lower = start_price + i * interval_size upper = lower + interval_size # 跳过低于0的区间 if lower < 0: continue if i == num_intervals - 1: # 最后一个区间 interval_label = f"{int(lower) if lower.is_integer() else lower}以上" else: interval_label = f"{int(lower) if lower.is_integer() else lower}-{int(upper) if upper.is_integer() else upper}" intervals.append((lower, upper, interval_label)) # 计算每个区间的商品数量和销量 result_data = [] # 确保销量和销售额列是数值型 df[quantity_col] = pd.to_numeric(df[quantity_col], errors='coerce').fillna(0) df[sales_col] = pd.to_numeric(df[sales_col], errors='coerce').fillna(0) # 计算总销量和总销售额 total_quantity = df[quantity_col].sum() total_sales = df[sales_col].sum() # 计算每个区间的数据 for lower, upper, label in intervals: if label.endswith('以上'): mask = (df[price_column] >= lower) elif label.endswith('以下'): mask = (df[price_column] < upper) else: mask = (df[price_column] >= lower) & (df[price_column] < upper) products_count = mask.sum() quantity = df.loc[mask, quantity_col].sum() sales = df.loc[mask, sales_col].sum() quantity_percent = (quantity / total_quantity * 100) if total_quantity > 0 else 0 sales_percent = (sales / total_sales * 100) if total_sales > 0 else 0 result_data.append({ '价格区间($)': label, '产品数量': products_count, '月销量': f"{quantity:,.0f}", '销量占比': f"{quantity_percent:.2f}%", '月销售额($)': f"{sales:,.2f}", '月销售额占比': f"{sales_percent:.2f}%" }) # 创建结果DataFrame result_df = pd.DataFrame(result_data) # 显示结果表格 st.subheader('价格区间分析结果') st.dataframe(result_df) # 创建可视化表格图像 fig, ax = plt.figure(figsize=(12, 8), dpi=120, facecolor='white'), plt.gca() ax.axis('tight') ax.axis('off') # 创建表格 table = ax.table( cellText=result_df.values, colLabels=result_df.columns, cellLoc='center', loc='center', colColours=['#90EE90'] * len(result_df.columns), cellColours=[['#FFFF99' if i % 2 == 0 else '#FFFFFF' for j in range(len(result_df.columns))] for i in range(len(result_df))] ) # 调整表格样式 table.auto_set_font_size(False) table.set_fontsize(14) # 增大字体大小 table.scale(1.5, 1.8) # 增大表格比例 # 应用自定义字体到表格文本 for (i, j), cell in table.get_celld().items(): text = cell.get_text() text.set_fontproperties(chinese_font) # 保存图像到内存 buf = io.BytesIO() plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0.2) buf.seek(0) # 显示图像 st.subheader('价格区间分析图表') st.image(buf, use_container_width=True) # 创建横向柱状图展示各价格段销量占比 st.subheader('价格区间销量占比分析') # 准备数据 labels = [row['价格区间($)'] for row in result_data] # 从销量占比中提取数值(去掉百分号并转换为浮点数) quantity_percents = [float(row['销量占比'].replace('%', '')) for row in result_data] # 创建横向柱状图 fig_bar, ax_bar = plt.subplots(figsize=(10, 8), dpi=120) # 绘制横向柱状图 bars = ax_bar.barh(labels, quantity_percents, color='skyblue') # 添加数据标签 for bar in bars: width = bar.get_width() label_text = ax_bar.text(width + 0.5, bar.get_y() + bar.get_height()/2, f'{width:.2f}%', ha='left', va='center', fontsize=10) # 设置标签文本的字体 label_text.set_fontproperties(chinese_font) # 设置图表标题和标签 title = ax_bar.set_title('各价格段销量占比', fontsize=16) xlabel = ax_bar.set_xlabel('销量占比(%)', fontsize=14) ylabel = ax_bar.set_ylabel('价格段', fontsize=14) # 应用中文字体到标题和标签 title.set_fontproperties(chinese_font) xlabel.set_fontproperties(chinese_font) ylabel.set_fontproperties(chinese_font) # 应用中文字体到y轴刻度标签 for label in ax_bar.get_yticklabels(): label.set_fontproperties(chinese_font) # 调整布局 plt.tight_layout() # 保存横向柱状图到内存 bar_buf = io.BytesIO() plt.savefig(bar_buf, format='png', bbox_inches='tight', pad_inches=0.2) bar_buf.seek(0) # 显示横向柱状图 st.image(bar_buf, use_container_width=True) # 提供柱状图下载链接 st.download_button( label="下载价格区间销量占比图表", data=bar_buf, file_name="价格区间销量占比.png", mime="image/png" ) # 提供表格图下载链接 st.download_button( label="下载价格区间分析图表", data=buf, file_name="价格区间分析.png", mime="image/png" ) # 也提供Excel下载 excel_buffer = io.BytesIO() result_df.to_excel(excel_buffer, index=False) excel_buffer.seek(0) st.download_button( label="下载价格区间分析Excel", data=excel_buffer, file_name="价格区间分析.xlsx", mime="application/vnd.ms-excel" ) except Exception as e: st.error(f'处理文件时出错: {e}') else: st.info('请上传Excel文件以开始分析')