Appearance
数据分析案例
通过一个完整的数据分析案例,综合运用所学的 Pandas 技能。
案例背景
假设我们有一份电商销售数据,需要进行全面的数据分析。
数据准备
python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 创建模拟数据
np.random.seed(42)
n = 1000
data = {
'订单ID': [f'ORD{i:05d}' for i in range(n)],
'日期': pd.date_range('2024-01-01', periods=n, freq='H'),
'产品类别': np.random.choice(['电子产品', '服装', '食品', '家居'], n),
'产品名称': np.random.choice(['产品A', '产品B', '产品C', '产品D'], n),
'销售数量': np.random.randint(1, 10, n),
'单价': np.random.randint(50, 500, n),
'客户地区': np.random.choice(['北京', '上海', '广州', '深圳'], n),
'客户类型': np.random.choice(['新客户', '老客户'], n, p=[0.3, 0.7])
}
df = pd.DataFrame(data)
df['销售额'] = df['销售数量'] * df['单价']
print("数据概览:")
print(df.head())
print(f"\n数据形状: {df.shape}")数据清洗
python
# 检查缺失值
print("缺失值统计:")
print(df.isnull().sum())
# 检查异常值
print("\n销售额统计:")
print(df['销售额'].describe())
# 去除异常值(销售额为负或过大的)
q1 = df['销售额'].quantile(0.01)
q99 = df['销售额'].quantile(0.99)
df_clean = df[(df['销售额'] >= q1) & (df['销售额'] <= q99)]
print(f"\n清洗后数据量: {len(df_clean)}")数据分析
总体统计
python
print("=== 总体统计 ===")
print(f"总订单数: {len(df_clean)}")
print(f"总销售额: {df_clean['销售额'].sum():,.2f}元")
print(f"平均订单金额: {df_clean['销售额'].mean():.2f}元")
print(f"总销售数量: {df_clean['销售数量'].sum()}")按类别分析
python
print("\n=== 产品类别分析 ===")
category_stats = df_clean.groupby('产品类别').agg({
'销售额': ['sum', 'mean', 'count'],
'销售数量': 'sum'
}).round(2)
print(category_stats)
# 可视化
category_sales = df_clean.groupby('产品类别')['销售额'].sum()
category_sales.plot(kind='bar', figsize=(10, 6), title='各类别销售额')
plt.ylabel('销售额')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()时间趋势分析
python
print("\n=== 时间趋势分析 ===")
df_clean['日期'] = pd.to_datetime(df_clean['日期'])
daily_sales = df_clean.groupby(df_clean['日期'].dt.date)['销售额'].sum()
# 可视化
daily_sales.plot(figsize=(12, 6), title='日销售额趋势')
plt.ylabel('销售额')
plt.tight_layout()
plt.show()
# 计算移动平均
daily_sales_ma = daily_sales.rolling(window=7).mean()
daily_sales_ma.plot(figsize=(12, 6), title='7日移动平均销售额')
plt.ylabel('销售额')
plt.tight_layout()
plt.show()地区分析
python
print("\n=== 地区分析 ===")
region_stats = df_clean.groupby('客户地区').agg({
'销售额': ['sum', 'mean'],
'订单ID': 'count'
}).round(2)
print(region_stats)
# 地区销售额占比
region_sales = df_clean.groupby('客户地区')['销售额'].sum()
region_sales.plot(kind='pie', autopct='%1.1f%%', title='各地区销售额占比')
plt.ylabel('')
plt.show()客户分析
python
print("\n=== 客户类型分析 ===")
customer_stats = df_clean.groupby('客户类型').agg({
'销售额': ['sum', 'mean'],
'订单ID': 'count'
}).round(2)
print(customer_stats)
# 客户类型对比
customer_type_sales = df_clean.groupby('客户类型')['销售额'].sum()
customer_type_sales.plot(kind='bar', figsize=(8, 6), title='新老客户销售额对比')
plt.ylabel('销售额')
plt.xticks(rotation=0)
plt.tight_layout()
plt.show()生成报告
python
print("\n" + "="*50)
print("数据分析报告")
print("="*50)
print(f"\n数据周期: {df_clean['日期'].min()} 至 {df_clean['日期'].max()}")
print(f"总订单数: {len(df_clean)}")
print(f"总销售额: {df_clean['销售额'].sum():,.2f}元")
print("\n热销产品类别:")
top_category = df_clean.groupby('产品类别')['销售额'].sum().sort_values(ascending=False)
for i, (cat, sales) in enumerate(top_category.head(3).items(), 1):
print(f" {i}. {cat}: {sales:,.2f}元")
print("\n最佳销售地区:")
top_region = df_clean.groupby('客户地区')['销售额'].sum().sort_values(ascending=False)
for i, (region, sales) in enumerate(top_region.head(3).items(), 1):
print(f" {i}. {region}: {sales:,.2f}元")通过这个案例,我们综合运用了数据读取、清洗、分析、可视化的完整流程。