使用numpy , pandas, matplotlib 实现数据清洗、特征构造、绘图可视化

#!/usr/bin/env python3
# -*- coding: utf-8 -*-


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 读取数据并预处理
df = pd.read_csv("/Users/shirley/Documents/train_user.csv")
df['time'] = pd.to_datetime(df['time'])  # 转换时间格式

# 筛选指定日期范围
start_date = '2014-11-18'
end_date = '2014-12-18'
filtered_df = df[(df['time'] >= start_date) & (df['time'] <= end_date)]

# 定义统计函数
def calculate_statistics(behavior_type, behavior_name):
    # 筛选特定行为
    behavior_data = filtered_df[filtered_df['behavior_type'] == behavior_type]
    # 统计每个用户的行为次数
    user_counts = behavior_data.groupby('user_id').size()
    
    # 计算统计量
    stats = {
        '行为类型': behavior_name,
        '均值': user_counts.mean(),
        '方差': user_counts.var(),
        '最小值': user_counts.min(),
        '最大值': user_counts.max(),
        '25%分位数': user_counts.quantile(0.25),
        '中位数': user_counts.median(),
        '75%分位数': user_counts.quantile(0.75)
    }
    return pd.Series(stats)

# 计算所有行为类型的统计量
stats_list = []
for behavior_type, name in zip([1, 2, 3, 4], ['点击', '收藏', '加购物车', '购买']):
    stats = calculate_statistics(behavior_type, name)
    stats_list.append(stats)

# 转换为DataFrame并打印
stats_df = pd.DataFrame(stats_list).set_index('行为类型')
print("用户行为统计量(2014-11-18至2014-12-18):")
print(stats_df)

# 绘制购买行为密度分布图
plt.figure(figsize=(10, 6))

# 获取购买行为数据
buy_counts = filtered_df[filtered_df['behavior_type'] == 4].groupby('user_id').size()
 
if not buy_counts.empty:
    # 绘制直方图
    plt.hist(buy_counts, bins=30, density=True, alpha=0.5, 
             color='skyblue', edgecolor='black', label='直方图')
    
    # 正确计算ECDF(经验累积分布函数)
    sorted_data = np.sort(buy_counts)
    ecdf = np.arange(1, len(sorted_data)+1) / len(sorted_data)
    
    plt.plot(sorted_data, ecdf, 
             color='orange', 
             linestyle='--',
             label='经验累积分布')
 
    plt.title('购买行为密度分布图', fontsize=14, pad=20)
    plt.xlabel('购买次数', fontsize=12)
    plt.ylabel('密度', fontsize=12)
    plt.legend()
    plt.grid(linestyle='--', alpha=0.3)
else:
    print("警告:指定日期范围内没有购买行为记录")
 
plt.tight_layout()
plt.show()