基于Python,读取表格内“进货价”与“零售价”计算毛利率,并进行排序。
统计毛利率区间商品数量绘制柱状图。
本代码旨在,优化店铺商品毛利率的结构。
import pandas as pd
import matplotlib.pyplot as plt
# 定义文件路径
file_path = "D:\\永辉\\yong\\202461.xlsx"
try:
# 尝试使用默认编码读取文件
df = pd.read_excel(file_path)
except UnicodeDecodeError:
# 如果出现UnicodeDecodeError,则尝试使用ANSI编码读取文件
df = pd.read_excel(file_path, encoding='ANSI')
# 检查“进货价”列是否存在于DataFrame中
if '进货价' in df.columns and '零售价' in df.columns:
# 将进货价列中的空白单元格填充为0.00
df['进货价'].fillna(0.00, inplace=True)
# 计算毛利率并转换为百分比形式,保留两位小数
df['毛利率'] = ((df['零售价'] - df['进货价']) / df['零售价']).mul(100).round(2)
# 基于毛利率列对行进行排序
df.sort_values(by='毛利率', ascending=False, inplace=True)
# 定义毛利率区间
bins = [0, 5, 10, 15, 20, 30, 40, 50, 60, 100, float('inf')]
labels = ['1-5%', '5-10%', '10-15%', '15-20%', '20-30%', '30-40%', '40-50%', '50-60%', '60-100%', '100%以上']
# 统计每个区间的商品数量
counts = pd.cut(df['毛利率'], bins=bins, labels=labels, right=False).value_counts().sort_index()
# 设置matplotlib的中文显示
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置字体为黑体
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# 绘制柱状图
plt.figure(figsize=(10, 6))
counts.plot(kind='bar')
plt.title('不同毛利率区间的商品数量')
plt.xlabel('毛利率区间')
plt.ylabel('商品数量')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# 保存修改后的DataFrame到新的Excel文件中
output_file_path = "D:\\永辉\\yong\\202461_modified.xlsx"
df.to_excel(output_file_path, index=False)
# 打印保存成功的消息
print(f"修改后的数据已保存到文件:{output_file_path}")
else:
print("未找到'进货价'或'零售价'列,请检查文件格式。")
然后,如果考虑精细化,针对单个类目进行统计效果会更好。
以此,结合销量数据,进行清除一些销量底、毛利率较低的商品。