团队合作与管理方式常常成为技术圈内外讨论的话题。抛开性别标签,高效协作的核心往往在于规则清晰与预期稳定。这不仅是管理学的范畴,在数据处理层面,清晰的定义和计算逻辑同样至关重要。
本文将从一个具体的数据分析需求出发,探讨如何使用Python来解决一个典型的业务比较问题。
算法场景:比较部门平均工资与公司平均工资
假设我们有一组员工数据,记录了每个人的所属部门和工资。业务需求是:找出哪些部门的平均工资高于公司的整体平均工资。
这个问题可以分解为两个步骤:
- 计算公司整体的平均工资。
- 计算每个部门的平均工资,并与公司平均值进行比较。
数据准备与基础算法实现
我们首先将数据模拟为一组字典列表:
employees = [
{"id": 1, "name": "小明", "dept": "技术", "salary": 15000},
{"id": 2, "name": "小红", "dept": "技术", "salary": 20000},
{"id": 3, "name": "小李", "dept": "产品", "salary": 12000},
{"id": 4, "name": "小王", "dept": "产品", "salary": 13000},
{"id": 5, "name": "小赵", "dept": "人力", "salary": 8000},
]
我们的目标是遍历一次数据,同时累加出公司总工资、总人数以及各部门的工资总和与人数。这里使用 collections.defaultdict 来方便地管理部门维度的统计。
from collections import defaultdict
def dept_vs_company(employees):
# 公司维度统计
total_salary = 0
total_count = 0
# 部门维度统计
dept_salary_sum = defaultdict(int)
dept_count = defaultdict(int)
for e in employees:
# 数据清洗:跳过关键字段缺失的记录
salary = e.get("salary")
dept = e.get("dept")
if salary is None or dept is None:
continue
# 累计公司总和
total_salary += salary
total_count += 1
# 累计部门总和
dept_salary_sum[dept] += salary
dept_count[dept] += 1
# 处理无有效数据的情况
if total_count == 0:
return {}
company_avg = total_salary / total_count
result = {}
for dept, salary_sum in dept_salary_sum.items():
dept_avg = salary_sum / dept_count[dept]
# 判断与公司平均值的相对关系
if dept_avg > company_avg:
relation = "higher_than_company"
elif dept_avg < company_avg:
relation = "lower_than_company"
else:
relation = "equal_to_company"
result[dept] = {
"dept_avg": dept_avg,
"company_avg": company_avg,
"relation": relation,
}
return result
运行以上函数并查看结果:
if __name__ == "__main__":
res = dept_vs_company(employees)
for dept, info in res.items():
print(
f"{dept} 部门平均工资 {info['dept_avg']:.2f},"
f"公司平均工资 {info['company_avg']:.2f},"
f"关系: {info['relation']}"
)
输出示例:
技术 部门平均工资 17500.00,公司平均工资 13600.00,关系: higher_than_company
产品 部门平均工资 12500.00,公司平均工资 13600.00,关系: lower_than_company
人力 部门平均工资 8000.00,公司平均工资 13600.00,关系: lower_than_company
从结果可以一目了然地看出,只有“技术”部门的平均工资高于公司整体水平。
算法变体:计算具体差值
有时业务需要更精确的数值对比,例如直接计算部门平均与公司平均的差额。只需对上述函数稍作修改:
def dept_diff_from_company(employees):
from collections import defaultdict
total_salary = 0
total_count = 0
dept_salary_sum = defaultdict(int)
dept_count = defaultdict(int)
for e in employees:
salary = e.get("salary")
dept = e.get("dept")
if salary is None or dept is None:
continue
total_salary += salary
total_count += 1
dept_salary_sum[dept] += salary
dept_count[dept] += 1
if total_count == 0:
return {}
company_avg = total_salary / total_count
result = {}
for dept, salary_sum in dept_salary_sum.items():
dept_avg = salary_sum / dept_count[dept]
diff = dept_avg - company_avg # 正数表示高于公司平均,负数表示低于
result[dept] = {
"dept_avg": dept_avg,
"company_avg": company_avg,
"diff": diff,
}
return result
这个版本输出的 diff 字段非常适合用于排序或生成可视化报表,直观展示各部门的薪酬水平与公司基准的差距。
使用 Pandas 进行高效数据分析
对于日常的数据分析工作,使用 pandas 库可以让代码更加简洁高效。pandas 内置的分组聚合功能能轻松应对此类问题。
import pandas as pd
def dept_vs_company_pandas(employees):
# 将数据转换为DataFrame
df = pd.DataFrame(employees)
# 数据清洗:移除关键字段为空的行
df = df.dropna(subset=["salary", "dept"])
# 计算公司平均工资
company_avg = df["salary"].mean()
# 按部门分组计算平均工资
dept_avg_series = df.groupby("dept")["salary"].mean()
result = {}
for dept, avg in dept_avg_series.items():
if avg > company_avg:
relation = "higher_than_company"
elif avg < company_avg:
relation = "lower_than_company"
else:
relation = "equal_to_company"
result[dept] = {
"dept_avg": float(avg),
"company_avg": float(company_avg),
"relation": relation,
}
return result
pandas 的实现逻辑与纯 Python 版本完全一致,但借助其强大的 数据分析 能力,代码更加清晰,尤其适合处理大规模数据集。
总结
本文通过一个“部门与公司平均工资比较”的案例,演示了从问题分析、基础算法实现到利用高级库(pandas)优化的完整数据处理流程。无论是使用基础数据结构进行精细控制,还是借助 pandas 提升开发效率,核心都在于对问题逻辑的清晰把握。在实际工作中,清晰、可维护的代码和可靠的数据处理逻辑,是支撑业务决策、实现高效团队协作的坚实基础。