分析题目字段 日期、销售员、产品、数量、单价、地区功能1. 清洗删除关键字段缺失、数量≤0、全字段去重2. 统计销售员销售额、地区销售额、月度总额3. 输出4个sheet 明细清洗后 、 按销售员 、 按地区 、 总览4. 异常处理空文件、无有效数据、缺失字段打印友好提示不会直接崩溃代码import pandas as pdimport osdef main():input_file sales_raw.xlsxoutput_file report.xlsx# 异常1原始文件不存在 if not os.path.exists(input_file):print(f【错误】找不到文件 {input_file}请确认文件和脚本放在同一个文件夹)returntry:# 读取原始exceldf_raw pd.read_excel(input_file, engineopenpyxl)except Exception as e:print(f【错误】读取文件失败{e})return# 异常2文件为空 if df_raw.empty:print(【提示】原始文件为空没有任何数据)return# 校验字段是否齐全 required_cols [日期, 销售员, 产品, 数量, 单价, 地区]missing_cols [c for c in required_cols if c not in df_raw.columns]if len(missing_cols) 0:print(f【错误】缺少必要字段{missing_cols}请检查Excel表头)return# 1.数据清洗 # ① 删除关键字段缺失的行df_clean df_raw.dropna(subsetrequired_cols).copy()# ② 剔除数量 0 的异常行df_clean df_clean[df_clean[数量] 0].copy()# ③ 按全部字段去重df_clean df_clean.drop_duplicates(subsetrequired_cols).copy()# 异常3清洗之后没有有效数据 if df_clean.empty:print(【提示】清洗完成后没有保留任何有效数据)return# 计算每条记录销售额数量 × 单价df_clean[销售额] df_clean[数量] * df_clean[单价]# 2.统计计算 # 按销售员汇总销售额stat_salesman df_clean.groupby(销售员).agg(销售额(销售额, sum)).reset_index()# 按地区汇总销售额stat_area df_clean.groupby(地区).agg(销售额(销售额, sum)).reset_index()# 月度总额total_month df_clean[销售额].sum()df_overview pd.DataFrame({统计项: [月度销售总额],金额: [total_month]})# 3.输出report.xlsx4个sheet with pd.ExcelWriter(output_file, engineopenpyxl) as writer:df_clean.to_excel(writer, sheet_name明细清洗后, indexFalse)stat_salesman.to_excel(writer, sheet_name按销售员, indexFalse)stat_area.to_excel(writer, sheet_name按地区, indexFalse)df_overview.to_excel(writer, sheet_name总览, indexFalse)print(f✅处理完成已生成 {output_file})print(f月度销售总额{total_month:.2f})if __name__ __main__:main()与ai交流