Day 40:Pandas 数据可视化与综合实战
Pandas 最后一天。先学用 Pandas 内置的绘图功能做数据可视化,然后完成一个完整的电商数据分析实战项目,把 5 天 Pandas 所学的全部串起来。
一、Pandas 内置绘图------.plot()
Pandas 基于 Matplotlib,可以直接对 DataFrame/Series 调用 .plot()。
python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 设置中文字体(Windows)
plt.rcParams["font.sans-serif"] = ["SimHei", "Microsoft YaHei"]
plt.rcParams["axes.unicode_minus"] = False
常用图表类型
python
# 折线图(趋势)
monthly_revenue = pd.Series([120, 150, 135, 168, 190, 210, 195, 220, 240, 230, 260, 280],
index=range(1, 13))
monthly_revenue.plot(kind="line", title="月度销售额趋势", xlabel="月份", ylabel="销售额(万元)")
# plt.show()
# 柱状图(对比)
product_sales = pd.Series({"手机": 450, "电脑": 520, "平板": 280, "耳机": 350})
product_sales.plot(kind="bar", title="产品销售额对比", color=["#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4"])
# plt.show()
# 饼图(占比)
product_sales.plot(kind="pie", autopct="%1.1f%%", title="产品销售额占比")
# plt.show()
# 直方图(分布)
scores = pd.Series(np.random.normal(75, 10, 500))
scores.plot(kind="hist", bins=20, title="成绩分布", edgecolor="white")
# plt.show()
# 散点图(关系)
df = pd.DataFrame({"学习时间": np.random.uniform(0, 10, 50),
"考试成绩": np.random.uniform(40, 100, 50)})
df.plot(kind="scatter", x="学习时间", y="考试成绩", title="学习时间 vs 考试成绩")
# plt.show()
二、综合实战------电商数据完整分析
模拟一个电商平台一年的销售数据,做完整的分析流程。
python
import pandas as pd
import numpy as np
np.random.seed(42)
# === 1. 生成模拟数据 ===
n = 5000
dates = pd.date_range("2026-01-01", "2026-12-31", periods=n)
products = np.random.choice(["手机", "电脑", "平板", "耳机", "手表"], n, p=[0.15, 0.1, 0.2, 0.3, 0.25])
regions = np.random.choice(["华东", "华南", "华北", "西南", "华中"], n)
customers = np.random.choice(["新用户", "老用户"], n, p=[0.4, 0.6])
# 价格和数量
base_prices = {"手机": 3000, "电脑": 5000, "平板": 2000, "耳机": 500, "手表": 1500}
prices = np.array([base_prices[p] + np.random.normal(0, base_prices[p]*0.1) for p in products])
quantities = np.random.randint(1, 5, n)
orders = pd.DataFrame({
"order_id": range(1, n + 1),
"date": dates,
"product": products,
"region": regions,
"customer_type": customers,
"price": prices.round(2),
"quantity": quantities,
})
orders["revenue"] = orders["price"] * orders["quantity"]
orders["month"] = orders["date"].dt.month
orders["month_name"] = orders["date"].dt.month_name()
print(f"订单数:{len(orders)}")
print(f"日期范围:{orders['date'].min().date()} ~ {orders['date'].max().date()}")
print(f"总销售额:{orders['revenue'].sum():,.0f} 元")
# === 2. 总体指标 ===
print("\n" + "=" * 60)
print("📊 年度销售总览")
print("=" * 60)
print(f"总订单数:{len(orders):,}")
print(f"总销售额:{orders['revenue'].sum():,.0f} 元")
print(f"平均订单值:{orders['revenue'].mean():,.0f} 元")
print(f"最高订单:{orders['revenue'].max():,.0f} 元")
# === 3. 月度趋势 ===
print("\n" + "=" * 60)
print("📈 月度销售趋势")
print("=" * 60)
monthly = orders.groupby("month_name").agg(
销售额=("revenue", "sum"),
订单数=("order_id", "count"),
平均订单值=("revenue", "mean"),
).round(0).sort_index()
print(monthly.to_string())
best_month = monthly["销售额"].idxmax()
print(f"\n销售最高月份:{best_month}({monthly.loc[best_month, '销售额']:,.0f} 元)")
# 月度趋势图
monthly["销售额"].plot(kind="line", marker="o", title="月度销售额趋势",
xlabel="月份", ylabel="销售额(元)")
# plt.show()
# === 4. 产品分析 ===
print("\n" + "=" * 60)
print("📦 产品分析")
print("=" * 60)
product_stats = orders.groupby("product").agg(
销售额=("revenue", "sum"),
销量=("quantity", "sum"),
订单数=("order_id", "count"),
均价=("price", "mean"),
占比=("revenue", lambda x: x.sum() / orders["revenue"].sum() * 100),
).round(1).sort_values("销售额", ascending=False)
print(product_stats.to_string())
# 产品饼图
product_stats["销售额"].plot(kind="pie", autopct="%1.1f%%", title="产品销售额占比")
# plt.show()
# === 5. 地区分析 ===
print("\n" + "=" * 60)
print("🗺️ 地区分析")
print("=" * 60)
region_stats = orders.groupby("region").agg(
销售额=("revenue", "sum"),
订单数=("order_id", "count"),
平均订单值=("revenue", "mean"),
占比=("revenue", lambda x: x.sum() / orders["revenue"].sum() * 100),
).round(1).sort_values("销售额", ascending=False)
print(region_stats.to_string())
# === 6. 用户分析 ===
print("\n" + "=" * 60)
print("👤 用户类型分析")
print("=" * 60)
customer_stats = orders.groupby("customer_type").agg(
销售额=("revenue", "sum"),
订单数=("order_id", "count"),
平均订单值=("revenue", "mean"),
占比=("revenue", lambda x: x.sum() / orders["revenue"].sum() * 100),
).round(1)
print(customer_stats.to_string())
# === 7. 产品 × 地区交叉分析 ===
print("\n" + "=" * 60)
print("🔀 产品 × 地区 交叉分析(销售额,万元)")
print("=" * 60)
pivot = orders.pivot_table(
values="revenue",
index="region",
columns="product",
aggfunc="sum",
fill_value=0,
) / 10000 # 转为万元
print(pivot.round(1).to_string())
# === 8. 关键发现总结 ===
print("\n" + "=" * 60)
print("📋 关键发现")
print("=" * 60)
top_product = product_stats.index[0]
top_region = region_stats.index[0]
print(f"1. 最畅销产品是「{top_product}」,占比 {product_stats.loc[top_product, '占比']:.1f}%")
print(f"2. 最大市场是「{top_region}」,贡献 {region_stats.loc[top_region, '占比']:.1f}% 销售额")
print(f"3. 老用户贡献了 {customer_stats.loc['老用户', '占比']:.1f}% 销售额,是新用户的{customer_stats.loc['老用户', '占比'] / customer_stats.loc['新用户', '占比']:.1f}倍")
print(f"4. 月均销售额 {(orders['revenue'].sum() / 12):,.0f} 元")
三、Pandas 五天回顾
| 天数 | 内容 | 核心技能 |
|---|---|---|
| Day 36 | Pandas 入门 | Series、DataFrame 创建、基本索引 |
| Day 37 | 数据读取 | read_csv/Excel/JSON、编码处理 |
| Day 38 | 数据清洗 | 缺失值、重复值、类型转换、异常值 |
| Day 39 | 数据操作 | 筛选、排序、groupby、agg、pivot_table |
| Day 40 | 可视化与实战 | plot 内置绘图、完整数据分析项目 |
四、第二阶段回顾 & 明日预告
第二阶段(Day 31-40)从 NumPy 走到 Pandas:
- NumPy(5天):数组创建 → 索引切片 → 广播运算 → 统计分析 → 综合实战
- Pandas(5天):数据结构 → 数据读取 → 数据清洗 → 数据操作 → 可视化实战
从现在起你已经具备了数据科学的基本能力。明天开始第三阶段------数学基础,为机器学习做好准备。
40天前,你从
print("Hello World")开始。现在你能用 NumPy 做矩阵运算,用 Pandas 分析千万级数据。进步可能每天察觉不到,但回头看,路已经走了很远。
第40天,打卡完成。里程碑达成!
本系列是个人学习笔记,如有错误欢迎在评论区指正交流。