1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
| class EDAAnalyzer: """探索性数据分析工具类""" def __init__(self, data): self.data = data def sales_trend_analysis(self): """销售趋势分析""" daily_sales = self.data.groupby('order_date').agg({ 'total_amount': 'sum', 'order_id': 'count' }).rename(columns={'order_id': 'order_count'}) monthly_sales = self.data.groupby([self.data['order_date'].dt.to_period('M')]).agg({ 'total_amount': 'sum', 'order_id': 'count' }).rename(columns={'order_id': 'order_count'}) fig, axes = plt.subplots(2, 2, figsize=(15, 10)) fig.suptitle('销售趋势分析', fontsize=16, fontweight='bold') axes[0, 0].plot(daily_sales.index, daily_sales['total_amount'], alpha=0.7) axes[0, 0].set_title('日销售额趋势') axes[0, 0].set_ylabel('销售额') axes[0, 0].tick_params(axis='x', rotation=45) monthly_sales.index = monthly_sales.index.to_timestamp() axes[0, 1].plot(monthly_sales.index, monthly_sales['total_amount'], marker='o', linewidth=2) axes[0, 1].set_title('月销售额趋势') axes[0, 1].set_ylabel('销售额') axes[0, 1].tick_params(axis='x', rotation=45) quarterly_sales = self.data.groupby(['year', 'quarter'])['total_amount'].sum().reset_index() quarterly_sales['year_quarter'] = quarterly_sales['year'].astype(str) + 'Q' + quarterly_sales['quarter'].astype(str) axes[1, 0].bar(quarterly_sales['year_quarter'], quarterly_sales['total_amount']) axes[1, 0].set_title('季度销售额对比') axes[1, 0].set_ylabel('销售额') axes[1, 0].tick_params(axis='x', rotation=45) weekday_sales = self.data.groupby('day_of_week')['total_amount'].sum() weekday_names = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'] axes[1, 1].bar(weekday_names, weekday_sales.values) axes[1, 1].set_title('星期几销售模式') axes[1, 1].set_ylabel('销售额') plt.tight_layout() plt.show() return daily_sales, monthly_sales def category_analysis(self): """产品类别分析""" category_stats = self.data.groupby('product_category').agg({ 'total_amount': ['sum', 'mean', 'count'], 'quantity': 'sum' }).round(2) category_stats.columns = ['总销售额', '平均订单金额', '订单数量', '总销量'] category_stats = category_stats.sort_values('总销售额', ascending=False) fig, axes = plt.subplots(2, 2, figsize=(15, 10)) fig.suptitle('产品类别分析', fontsize=16, fontweight='bold') axes[0, 0].pie(category_stats['总销售额'], labels=category_stats.index, autopct='%1.1f%%', startangle=90) axes[0, 0].set_title('各类别销售额占比') axes[0, 1].bar(category_stats.index, category_stats['订单数量']) axes[0, 1].set_title('各类别订单数量') axes[0, 1].tick_params(axis='x', rotation=45) axes[1, 0].bar(category_stats.index, category_stats['平均订单金额']) axes[1, 0].set_title('各类别平均订单金额') axes[1, 0].tick_params(axis='x', rotation=45) axes[1, 1].bar(category_stats.index, category_stats['总销量']) axes[1, 1].set_title('各类别总销量') axes[1, 1].tick_params(axis='x', rotation=45) plt.tight_layout() plt.show() print("产品类别统计:") print(category_stats) return category_stats def regional_analysis(self): """地区分析""" regional_stats = self.data.groupby('region').agg({ 'total_amount': ['sum', 'mean'], 'order_id': 'count', 'customer_id': 'nunique' }).round(2) regional_stats.columns = ['总销售额', '平均订单金额', '订单数量', '客户数量'] regional_stats = regional_stats.sort_values('总销售额', ascending=False) fig, axes = plt.subplots(2, 2, figsize=(15, 10)) fig.suptitle('地区销售分析', fontsize=16, fontweight='bold') axes[0, 0].bar(regional_stats.index, regional_stats['总销售额']) axes[0, 0].set_title('各地区总销售额') axes[0, 0].tick_params(axis='x', rotation=45) axes[0, 1].bar(regional_stats.index, regional_stats['客户数量']) axes[0, 1].set_title('各地区客户数量') axes[0, 1].tick_params(axis='x', rotation=45) axes[1, 0].bar(regional_stats.index, regional_stats['平均订单金额']) axes[1, 0].set_title('各地区平均订单金额') axes[1, 0].tick_params(axis='x', rotation=45) axes[1, 1].pie(regional_stats['总销售额'], labels=regional_stats.index, autopct='%1.1f%%', startangle=90) axes[1, 1].set_title('各地区销售额占比') plt.tight_layout() plt.show() print("地区销售统计:") print(regional_stats) return regional_stats def customer_analysis(self): """客户分析""" customer_stats = self.data.groupby('customer_id').agg({ 'total_amount': ['sum', 'mean', 'count'], 'order_date': ['min', 'max'] }).round(2) customer_stats.columns = ['总消费金额', '平均订单金额', '订单次数', '首次购买', '最后购买'] customer_stats['购买周期(天)'] = ( customer_stats['最后购买'] - customer_stats['首次购买'] ).dt.days def classify_customer(row): if row['总消费金额'] >= customer_stats['总消费金额'].quantile(0.8): return '高价值客户' elif row['总消费金额'] >= customer_stats['总消费金额'].quantile(0.5): return '中价值客户' else: return '低价值客户' customer_stats['客户类型'] = customer_stats.apply(classify_customer, axis=1) fig, axes = plt.subplots(2, 2, figsize=(15, 10)) fig.suptitle('客户分析', fontsize=16, fontweight='bold') axes[0, 0].hist(customer_stats['总消费金额'], bins=50, alpha=0.7) axes[0, 0].set_title('客户消费金额分布') axes[0, 0].set_xlabel('总消费金额') axes[0, 0].set_ylabel('客户数量') axes[0, 1].hist(customer_stats['订单次数'], bins=30, alpha=0.7) axes[0, 1].set_title('客户订单次数分布') axes[0, 1].set_xlabel('订单次数') axes[0, 1].set_ylabel('客户数量') customer_type_counts = customer_stats['客户类型'].value_counts() axes[1, 0].pie(customer_type_counts.values, labels=customer_type_counts.index, autopct='%1.1f%%', startangle=90) axes[1, 0].set_title('客户类型分布') axes[1, 1].scatter(customer_stats['订单次数'], customer_stats['总消费金额'], alpha=0.6) axes[1, 1].set_title('客户价值分析') axes[1, 1].set_xlabel('订单次数') axes[1, 1].set_ylabel('总消费金额') plt.tight_layout() plt.show() print("客户统计信息:") print(f"总客户数: {len(customer_stats)}") print(f"平均客户价值: {customer_stats['总消费金额'].mean():.2f}") print(f"客户价值中位数: {customer_stats['总消费金额'].median():.2f}") print("\n客户类型分布:") print(customer_type_counts) return customer_stats
eda = EDAAnalyzer(cleaned_data) daily_sales, monthly_sales = eda.sales_trend_analysis() category_stats = eda.category_analysis() regional_stats = eda.regional_analysis() customer_stats = eda.customer_analysis()
|