Python案例如何用Pandas做数据分位

wen python案例 1

本文目录导读:

Python案例如何用Pandas做数据分位

  1. 基础分位操作
  2. 使用 cut() 进行等宽分箱
  3. 使用 qcut() 进行等频分位
  4. 实际案例:学生成绩分析
  5. 进阶应用:异常值检测
  6. 数据分段与可视化
  7. 自定义分位函数
  8. 实用技巧总结

我来详细讲解如何使用Pandas进行数据分位操作,包括多个实用案例。

基础分位操作

使用 quantile() 方法

import pandas as pd
import numpy as np
# 创建示例数据
df = pd.DataFrame({
    'score': [85, 92, 78, 95, 88, 73, 90, 82, 96, 70],
    'name': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
})
# 计算单个分位数
median = df['score'].quantile(0.5)  # 中位数
q1 = df['score'].quantile(0.25)     # 第一四分位数
q3 = df['score'].quantile(0.75)     # 第三四分位数
print(f"中位数: {median}")
print(f"Q1: {q1}")
print(f"Q3: {q3}")
# 计算多个分位数
quantiles = df['score'].quantile([0.25, 0.5, 0.75, 0.9])
print("\n多个分位数:")
print(quantiles)

使用 cut() 进行等宽分箱

# 将数据分箱
df['score_bins'] = pd.cut(df['score'], 
                          bins=4,  # 分成4组
                          labels=['低', '中低', '中高', '高'])
print("等宽分箱结果:")
print(df[['name', 'score', 'score_bins']])

使用 qcut() 进行等频分位

# 等频分箱(每个箱子包含相同数量的数据)
df['score_quantile'] = pd.qcut(df['score'], 
                               q=4,  # 分成4组
                               labels=['Q1', 'Q2', 'Q3', 'Q4'])
print("\n等频分箱结果:")
print(df[['name', 'score', 'score_quantile']])
# 查看分组统计
print("\n每组数量:")
print(df['score_quantile'].value_counts().sort_index())

实际案例:学生成绩分析

import pandas as pd
import numpy as np
# 创建更复杂的学生成绩数据集
np.random.seed(42)
students_data = pd.DataFrame({
    'student_id': range(1, 101),
    'name': [f'学生{i}' for i in range(1, 101)],
    'chinese': np.random.randint(60, 100, 100),
    'math': np.random.randint(50, 100, 100),
    'english': np.random.randint(55, 100, 100),
    'class': np.random.choice(['A班', 'B班', 'C班'], 100)
})
# 计算总分
students_data['total_score'] = (students_data['chinese'] + 
                                students_data['math'] + 
                                students_data['english'])
print("数据概览:")
print(students_data.head())
# 1. 成绩等级划分
students_data['grade'] = pd.qcut(students_data['total_score'],
                                 q=[0, 0.25, 0.5, 0.75, 1.0],
                                 labels=['D', 'C', 'B', 'A'])
# 2. 分班统计分析
print("\n各班级成绩等级分布:")
grade_by_class = pd.crosstab(students_data['class'], students_data['grade'])
print(grade_by_class)
# 3. 各科目百分位排名
students_data['chinese_percentile'] = students_data['chinese'].rank(pct=True)
students_data['math_percentile'] = students_data['math'].rank(pct=True)
students_data['english_percentile'] = students_data['english'].rank(pct=True)
print("\n前5名学生百分位排名:")
print(students_data.head()[['name', 'chinese_percentile', 'math_percentile', 'english_percentile']])

进阶应用:异常值检测

# 使用IQR方法检测异常值
def detect_outliers_iqr(data, column):
    Q1 = data[column].quantile(0.25)
    Q3 = data[column].quantile(0.75)
    IQR = Q3 - Q1
    lower_bound = Q1 - 1.5 * IQR
    upper_bound = Q3 + 1.5 * IQR
    return (data[column] < lower_bound) | (data[column] > upper_bound)
# 检测各科目的异常值
for subject in ['chinese', 'math', 'english']:
    outliers = detect_outliers_iqr(students_data, subject)
    print(f"\n{subject} 异常值数量: {outliers.sum()}")
    if outliers.any():
        print(f"异常值学生: {students_data[outliers]['name'].tolist()}")

数据分段与可视化

import matplotlib.pyplot as plt
# 创建分位统计表
def quantile_summary(data, columns, quantiles=[0.1, 0.25, 0.5, 0.75, 0.9]):
    summary = pd.DataFrame()
    for col in columns:
        summary[col] = data[col].quantile(quantiles)
    summary.index = [f'{int(q*100)}%' for q in quantiles]
    return summary
# 生成分位汇总
summary_stats = quantile_summary(students_data, ['chinese', 'math', 'english', 'total_score'])
print("分位汇总表:")
print(summary_stats)
# 可视化分位分布
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
subjects = ['chinese', 'math', 'english', 'total_score']
for ax, subject in zip(axes.flat, subjects):
    # 使用qcut获取分位数标签
    quantile_labels = pd.qcut(students_data[subject], q=5, labels=False)
    # 绘制直方图
    ax.hist(students_data[subject], bins=20, alpha=0.7, edgecolor='black')
    ax.axvline(students_data[subject].median(), color='red', linestyle='--', label='中位数')
    ax.axvline(students_data[subject].mean(), color='green', linestyle='--', label='均值')
    ax.set_title(f'{subject} 分布')
    ax.legend()
    ax.set_xlabel('分数')
    ax.set_ylabel('频数')
plt.tight_layout()
plt.show()

自定义分位函数

def custom_quantile_analysis(data, column, breaks=[0, 0.2, 0.4, 0.6, 0.8, 1.0]):
    """
    自定义分位分析函数
    """
    # 计算分位点
    quantiles = data[column].quantile(breaks)
    # 创建标签
    labels = [f'{int(breaks[i]*100)}%-{int(breaks[i+1]*100)}%' 
              for i in range(len(breaks)-1)]
    # 分箱
    data['quantile_group'] = pd.qcut(data[column], 
                                     q=breaks, 
                                     labels=labels)
    # 分组统计
    result = data.groupby('quantile_group')[column].agg(['count', 'min', 'max', 'mean', 'std'])
    return result
# 使用自定义函数
analysis_result = custom_quantile_analysis(students_data, 'total_score')
print("\n自定义分位分析结果:")
print(analysis_result)

实用技巧总结

常用分位方法对比

# 不同分位方法的比较
data = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print("不同分位方法比较:")
print(f"默认方法 (linear): {data.quantile(0.5)}")
print(f"lower方法: {data.quantile(0.5, interpolation='lower')}")
print(f"higher方法: {data.quantile(0.5, interpolation='higher')}")
print(f"nearest方法: {data.quantile(0.5, interpolation='nearest')}")
print(f"midpoint方法: {data.quantile(0.5, interpolation='midpoint')}")

这些案例涵盖了Pandas数据分位的主要应用场景,根据你的具体需求,可以选择合适的方法进行数据分析。

抱歉,评论功能暂时关闭!