本文目录导读:

我来详细介绍一下如何使用Pandas进行数据分组重映射,包含多个实用案例。
基础分组重映射
import pandas as pd
import numpy as np
# 创建示例数据
df = pd.DataFrame({
'部门': ['技术部', '市场部', '技术部', '市场部', '技术部', '财务部'],
'员工': ['张三', '李四', '王五', '赵六', '钱七', '孙八'],
'薪资': [15000, 12000, 18000, 11000, 16000, 13000],
'年龄': [28, 32, 35, 26, 30, 45]
})
print("原始数据:")
print(df)
使用groupby进行分组统计
# 按部门分组,计算平均薪资
dept_stats = df.groupby('部门')['薪资'].agg(['mean', 'max', 'min', 'count'])
print("\n部门薪资统计:")
print(dept_stats)
# 重映射:将统计结果映射回原数据
df['部门平均薪资'] = df.groupby('部门')['薪资'].transform('mean')
print("\n添加部门平均薪资列:")
print(df)
分组排名和重映射
# 按部门分组,内部排名
df['部门内薪资排名'] = df.groupby('部门')['薪资'].rank(ascending=False)
print("\n部门内部薪资排名:")
print(df)
# 按分组条件重映射值
def salary_level(avg_salary):
if avg_salary > 15000:
return '高薪部门'
elif avg_salary > 12000:
return '中等薪资部门'
else:
return '低薪部门'
# 创建部门薪资等级映射
dept_avg = df.groupby('部门')['薪资'].mean()
dept_level = dept_avg.apply(salary_level).to_dict()
df['部门等级'] = df['部门'].map(dept_level)
print("\n添加部门等级:")
print(df)
复杂分组重映射案例
# 创建更复杂的数据集
sales_data = pd.DataFrame({
'年份': [2023, 2023, 2023, 2024, 2024, 2024],
'季度': ['Q1', 'Q2', 'Q3', 'Q1', 'Q2', 'Q3'],
'产品': ['A', 'A', 'B', 'A', 'B', 'B'],
'销售额': [100, 150, 200, 120, 180, 220],
'成本': [60, 80, 100, 70, 90, 110]
})
print("\n销售数据:")
print(sales_data)
# 多级分组重映射
sales_data['产品年度销售额'] = sales_data.groupby(['年份', '产品'])['销售额'].transform('sum')
sales_data['产品年度利润'] = sales_data.groupby(['年份', '产品'])['销售额'].transform('sum') - \
sales_data.groupby(['年份', '产品'])['成本'].transform('sum')
print("\n添加年度汇总数据:")
print(sales_data)
条件分组重映射
# 自定义分组函数
def age_group(age):
if age < 30:
return '青年'
elif age < 40:
return '中年'
else:
return '中老年'
# 创建年龄组
df['年龄组'] = df['年龄'].apply(age_group)
# 按年龄组和部门分组统计
complex_stats = df.groupby(['年龄组', '部门']).agg({
'薪资': ['mean', 'count'],
'年龄': 'mean'
}).round(2)
print("\n年龄组与部门交叉统计:")
print(complex_stats)
# 重映射交叉统计结果
df['部门年龄组平均薪资'] = df.groupby(['部门', '年龄组'])['薪资'].transform('mean')
print("\n添加部门年龄组平均薪资:")
print(df)
实际应用场景:员工绩效评估
# 创建员工绩效数据
performance_data = pd.DataFrame({
'部门': ['技术部', '技术部', '技术部', '市场部', '市场部', '市场部'],
'员工': ['张三', '王五', '钱七', '李四', '赵六', '周九'],
'绩效分': [85, 92, 78, 88, 95, 72],
'项目数量': [5, 8, 4, 6, 9, 3]
})
print("\n员工绩效数据:")
print(performance_data)
# 计算部门绩效等级阈值
def get_performance_level(score, quantiles):
if score >= quantiles[0.75]:
return 'A级'
elif score >= quantiles[0.5]:
return 'B级'
else:
return 'C级'
# 按部门分组计算绩效等级
for dept in performance_data['部门'].unique():
mask = performance_data['部门'] == dept
dept_scores = performance_data.loc[mask, '绩效分']
quantiles = dept_scores.quantile([0.25, 0.5, 0.75])
performance_data.loc[mask, '绩效等级'] = performance_data.loc[mask, '绩效分'].apply(
lambda x: get_performance_level(x, quantiles)
)
print("\n添加绩效等级后的数据:")
print(performance_data)
数据标准化和重映射
# 数据标准化
df['薪资标准化'] = df.groupby('部门')['薪资'].transform(
lambda x: (x - x.mean()) / x.std()
)
print("\n薪资标准化结果:")
print(df[['部门', '员工', '薪资', '薪资标准化']])
# 分位数排名重映射
df['薪资分位数'] = df.groupby('部门')['薪资'].transform(
lambda x: pd.qcut(x, 4, labels=['低', '中低', '中高', '高'])
)
print("\n薪资分位数分组:")
print(df[['部门', '员工', '薪资', '薪资分位数']])
实用技巧:滚动分组重映射
# 时间序列分组重映射
time_data = pd.DataFrame({
'日期': pd.date_range('2024-01-01', periods=10, freq='D'),
'类别': ['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B'],
'数值': [10, 20, 15, 25, 12, 22, 18, 28, 14, 24]
})
# 按类别分组,计算3日滚动平均
time_data['滚动平均'] = time_data.groupby('类别')['数值'].transform(
lambda x: x.rolling(window=3, min_periods=1).mean()
)
print("\n滚动平均值计算结果:")
print(time_data)
这些案例涵盖了Pandas数据分组重映射的主要用法,包括:
- 基础分组统计和映射
- 分组排名和条件映射
- 多级分组和交叉统计
- 自定义分组函数
- 实际业务场景应用
- 数据标准化
- 时间序列滚动分组
掌握这些技巧可以帮助你高效地处理各种数据分组和重映射需求。