内容概要:数据分析全流程:数据清洗→异常处理→多维分析→可视化报告
构建模拟数据集
import pandas as pdimport numpy as np# 生成模拟电商数据np.random.seed(2025) # 固定随机种子data_dict = { 'order_id': [f'DD00{i}'for i in range(1, 1001)], # 订单编号 'user_type': np.random.choice([ '山海摸鱼人', '山海游侠', '山海闲云野鹤', '山海浪人', '山海悠然客' ], 1000), # 用户类型 'region': np.random.choice(['华东', '华南', '华北', '华中', '西北'], 1000), 'sales_volume': np.round(np.random.gamma(shape=2, scale=500, size=1000), 2), 'quantity': np.random.randint(1, 20, 1000), 'order_date': pd.date_range('2024-01-01', periods=1000, freq='8H')}# 创建原始DataFrameraw_df = pd.DataFrame(data_dict)# 人为添加数据问题raw_df.loc[10:15, 'user_type'] = np.nan # 缺失值raw_df.loc[[20,50], 'sales_volume'] = 99999.99 # 异常大值raw_df.loc[[30,60], 'sales_volume'] = -100 # 异常负值raw_df.loc[100:105, 'region'] = '未知地区' # 错误分类
数据清洗与异常处理
处理缺失值
# 创建清洗副本clean_df = raw_df.copy()# 填充缺失的用户类型clean_df['user_type'] = clean_df['user_type'].fillna('未知类型')# 删除完全重复的行clean_df = clean_df.drop_duplicates()print(f"清洗后数据量变化:{len(raw_df)} → {len(clean_df)}")
修正异常值
# 销售金额修正(排除异常值)sales_q1 = clean_df['sales_volume'].quantile(0.05)sales_q3 = clean_df['sales_volume'].quantile(0.95)clean_df['sales_volume'] = clean_df['sales_volume'].mask( (clean_df['sales_volume'] < sales_q1 clean_dfsales_volume> sales_q3), clean_df['sales_volume'].median())# 修正错误分类region_list = ['华东', '华南', '华北', '华中', '西北']clean_df['region'] = clean_df['region'].where( clean_df['region'].isin(region_list), '其他地区')
多维数据分析
用户维度分析
# 按用户类型分组统计user_type_df = clean_df.groupby('user_type').agg({ 'sales_volume': ['sum', 'mean'], 'quantity': 'sum'}).reset_index()user_type_df.columns = ['用户类型', '总销售额', '客单价', '总销量']print(user_type_df.sort_values('总销售额', ascending=False))
时间序列分析
# 按月统计销售额time_analysis = clean_df.set_index('order_date').resample('M')['sales_volume'].sum()print(f"\n月度销售趋势:\n{time_analysis.apply(lambda x: f'¥{x:,.2f}')}")
可视化报告生成
创建分析画布
import matplotlib.pyplot as pltplt.style.use('seaborn') # 应用样式# 覆盖样式中的字体配置plt.rcParams.update({ 'font.family': 'SimHei', # 主字体 'font.sans-serif': ['SimHei'], # 无衬线字体(覆盖seaborn默认) 'axes.unicode_minus': False # 修复负号})fig, axes = plt.subplots(2, 2, figsize=(16, 10))plt.suptitle('2024电商销售分析报告', fontsize=18, y=1.02)
用户类型分析
# 用户类型销售额分布user_type_df.plot.bar(x='用户类型', y='总销售额', ax=axes[0,0], color='#2b8cbe', title='用户类型销售额分布')axes[0,0].set_ylabel('销售额(万元)')# 用户类型-客单价散点图axes[0,1].scatter(user_type_df['总销量'], user_type_df['客单价'], s=user_type_df['总销售额']/1000)axes[0,1].set_title('用户价值气泡图')axes[0,1].set_xlabel('总销量')axes[0,1].set_ylabel('客单价')
时空分析
# 区域销售分布region_data = clean_df.groupby('region')['sales_volume'].sum()axes[1,0].pie(region_data, labels=region_data.index, autopct='%1.1f%%', colors=['#8dd3c7','#ffffb3','#bebada','#fb8072','#80b1d3'])# 月度趋势图time_analysis.plot(ax=axes[1,1], marker='o', color='#2ca25f', linewidth=2, title='月度销售趋势')axes[1,1].set_ylabel('销售额')# 保存报告plt.tight_layout()plt.savefig('sales_report.png', dpi=300, bbox_inches='tight')plt.show()
技巧总结
# 生成数据摘要报告report = clean_df.describe(percentiles=[.25, .5, .75])report.loc['range'] = report.loc['max'] - report.loc['min']print(report.round(2).T[['mean', '50%', 'range']])
数据质量三重校验:通过描述统计、数值分布、业务逻辑三个维度验证数据
动态阈值检测:使用分位数替代固定阈值处理异常值,适配数据分布变化
分析报告四要素:核心指标趋势(折线图),构成分析(饼图/堆积图),对比分析(柱状图),相关性分析(散点图/热力图)