
本文介绍如何使用pandas的melt()方法,将包含degree1/degree2…、specialisation1/specialisation2…等重复前缀的宽格式招聘数据,规范转换为每行一条教育经历的长格式结构,便于后续逐人逐学历迭代处理。
本文介绍如何使用pandas的`melt()`方法,将包含degree1/degree2…、specialisation1/specialisation2…等重复前缀的宽格式招聘数据,规范转换为每行一条教育经历的长格式结构,便于后续逐人逐学历迭代处理。
在处理招聘类Excel数据时,常遇到“一人多学历”的建模困境:原始表格将最多5个学位信息横向铺开(如degree1, specialisation1, college1, degree2, …),导致每行代表一个候选人但包含冗余列。若直接用df.iterrows()遍历,需手动解析列名、提取序号、分组聚合——不仅代码易错、可读性差,还难以适配Selenium自动化流程中“对每位候选人逐一提交其全部学历”的逻辑。
更专业、可持续的解法是先标准化数据结构,再面向清晰语义编程。核心思路是:将宽表(wide format)通过pd.melt()转为长表(long format),使每位候选人的每条学历记录独立成行,字段语义明确(如degree, specialisation, college, qualification_level),后续迭代即可自然按人→按学历两层展开。
✅ 正确实现步骤
假设已加载数据:
import pandas as pd
df = pd.read_excel("applicants.xlsx")-
识别固定字段与可展开字段
- 固定字段(id_vars):sr_no, old_emp_id, name, address, mobile, emp_status —— 每位候选人唯一不变的信息;
- 可展开字段:所有以degree, specialisation, college开头的列(如degree1, specialisation2, college5)。
-
执行熔解(melt)操作
# 提取所有教育相关列名(支持 degreeX / specialisationX / collegeX,X=1~5) edu_cols = [col for col in df.columns if any(col.startswith(prefix) for prefix in ['degree', 'specialisation', 'college'])]
熔解:保留固定字段,将教育列转为 attribute-value 对
df_long = pd.melt( df, id_vars=['sr_no', 'old_emp_id', 'name', 'address', 'mobile', 'emp_status'], value_vars=edu_cols, var_name='attribute', value_name='value' )
3. **解析字段层级,构建规整教育记录**
利用`attribute`列(如`degree2`)提取序号和类型,生成结构化字段:
```python
# 提取 qualification_id(如 'degree2' → 2)和 field_type(如 'degree')
df_long[['field_type', 'qualification_id']] = df_long['attribute'].str.extract(r'(\w+)(\d+)')
# 透视:将同一 candidate + qualification_id 的多属性聚合成一行
df_education = df_long.pivot_table(
index=['sr_no', 'old_emp_id', 'name', 'address', 'mobile', 'emp_status', 'qualification_id'],
columns='field_type',
values='value',
aggfunc='first' # 防止重复值干扰
).reset_index()
# 清理列名,重命名并确保字段完整
df_education.columns.name = None
df_education = df_education.rename(columns={
'degree': 'degree_name',
'specialisation': 'specialisation',
'college': 'university'
}).fillna('') # 空值统一为空字符串,避免None影响Selenium输入
# 可选:添加显式序号列,便于排序
df_education['qualification_order'] = df_education['qualification_id'].astype(int)
df_education = df_education.sort_values(['sr_no', 'qualification_order']).reset_index(drop=True)最终得到规整的长格式教育表: | sr_no | name | degree_name | specialisation | university | qualification_order | |-------|--------|---------------------|--------------------------|----------------|---------------------| | 1 | Amit | Computer Science | Robotics | IIT Delhi | 1 | | 1 | Amit | MSC ML | MIT | | 2 | | 1 | Amit | PHD AI | Harvard | | 3 | | 2 | Samit | Bachelor of Arts | Economics | Delih Univ | 1 | | ... | ... | ... | ... | ... | ... |
⚠️ 注意事项与最佳实践
- 避免iterrows()嵌套解析:原问题中尝试用索引除法推算学位序号(如(j-i)//7+1)极易出错,且无法应对缺失列或列顺序变化;melt + pivot方案完全基于列名语义,鲁棒性强。
- 字段命名一致性很重要:确保原始Excel中教育字段严格遵循{type}{n}模式(如college1, College1, COLLEGE1会导致正则匹配失败)。预处理时可用df.columns = df.columns.str.lower().str.strip()统一。
- 空值处理:pivot_table(..., aggfunc='first')能安全跳过空学位列;.fillna('')保证Selenium调用时不会因None触发异常。
- 性能提示:对于万级候选人数据,melt+pivot仍远快于Python层循环,且内存友好。如需进一步加速,可结合categorical编码qualification_id。
✅ 后续自动化集成示例(Selenium场景)
获得df_education后,即可自然分组迭代:
for (sr_no, name), edu_group in df_education.groupby(['sr_no', 'name']):
print(f"Processing {name} (ID: {sr_no})...")
for _, edu in edu_group.iterrows():
# selenium_driver.find_element(...).send_keys(edu['degree_name'])
# selenium_driver.find_element(...).send_keys(edu['specialisation'])
# ...
pass此结构彻底解耦了数据清洗与业务逻辑,显著提升代码可维护性与扩展性——当招聘系统新增degree4_start_year字段时,仅需更新正则表达式,无需重构整个循环逻辑。










