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
| import pandas as pd import numpy as np
np.random.seed(42) n = 20000 df = pd.DataFrame({ 'order_id': range(n), 'date': pd.date_range('2025-01-01', periods=n, freq='30min'), 'city': np.random.choice(['北京', '上海', '广州', '深圳', '成都', '杭州'], n), 'category': np.random.choice(['电子产品', '服装', '食品', '家居'], n, p=[0.3, 0.3, 0.2, 0.2]), 'amount': np.random.exponential(500, n).round(2), 'quantity': np.random.randint(1, 10, n) })
city_analysis = df.groupby('city').agg( total_sales=('amount', 'sum'), avg_order=('amount', 'mean'), order_count=('order_id', 'count') ).round(2).sort_values('total_sales', ascending=False) print("=== 城市销售排行 ===") print(city_analysis)
cat_analysis = df.groupby('category').agg( total_sales=('amount', 'sum'), avg_quantity=('quantity', 'mean'), order_count=('order_id', 'count') ).round(2) print("\n=== 品类分析 ===") print(cat_analysis)
cross = df.pivot_table( values='amount', index='city', columns='category', aggfunc='sum', margins=True, margins_name='合计' ).round(0) print("\n=== 城市×品类交叉分析 ===") print(cross)
monthly = df.set_index('date').resample('M')['amount'].agg(['sum', 'mean', 'count']) monthly.index = monthly.index.strftime('%Y-%m') print("\n=== 月度趋势 ===") print(monthly)
|