import pandas as pd
import numpy as np # 导入NumPy库
# 定义Excel文件路径
excel_path = r"D:\daku\福购\fugou3-24.xlsx"
output_path = r"D:\daku\福购\fugou3-24_updated.xlsx"
# 读取Excel文件
df = pd.read_excel(excel_path)
# 假设零售价列名为'零售价',进货价列名为'进货价'
retail_price_col = '零售价'
purchase_price_col = '进货价'
# 确保所需列存在于DataFrame中
if retail_price_col not in df.columns or purchase_price_col not in df.columns:
raise ValueError(f"缺少列名:{retail_price_col} 或 {purchase_price_col}")
# 计算毛利率,并创建新的毛利率列
# 使用np.where来处理0作为除数的情况,避免inf出现
df['毛利率'] = np.where(df[purchase_price_col] == 0, 0,
((df[retail_price_col] - df[purchase_price_col]) / df[purchase_price_col]) * 100)
# 计算综合毛利率(排除毛利率为NaN的行)
overall_gross_margin = df['毛利率'].dropna().mean()
# 将综合毛利率写入新列,这里我们选择在最后一列添加
df['总店毛利率'] = overall_gross_margin
# 将修改后的DataFrame写入新的Excel文件
df.to_excel(output_path, index=False)
print(f"综合毛利率是:{overall_gross_margin:.2f}%")
print(f"已将更新后的数据写入文件:{output_path}")
Python计算超市便利店商品毛利率
Python计算便利店综合毛利率
如果直接读取便利所有商品去算超市的综合毛利率是没有任何意义的呢!
正确的方式是针对便利店商品进行分类,根据分类商品计算便利店某个类目的毛利率,基于便利店类目的毛利率去进行类目之间的可视化对比。
如果继续考虑整店内的毛利率,也是应该基于类目的毛利率,而不是所有商品综合去计算。