如何用Python提取字符串内元素并处理职位需求数据?
Pandas职位信息提取与标准化解决方案
核心思路
针对你的需求,我们可以通过自定义函数+Pandas数据处理完成职位标准化、人数提取和目标职位筛选,解决三个核心问题:
- 合并"or"连接的同类职位(如
Auditor or Auditor(S)统一为Auditor) - 提取职位前的数字作为需求人数(无数字则默认1)
- 精准筛选指定职位(如
PayRoll_Manager)
代码实现
首先导入依赖库:
import pandas as pd import re
1. 定义职位标准化函数
该函数处理单个职位条目(如"2 Auditor or Auditor(S)"),返回标准化后的职位名称和需求人数:
def standardize_position(item): # 提取前缀数字(人数),无数字则默认1 num_match = re.match(r'(\d+)', item.strip()) count = int(num_match.group(1)) if num_match else 1 # 移除数字前缀,提取职位核心内容 position_part = re.sub(r'^\d+\s*', '', item.strip()) # 合并or连接的职位,取第一个作为标准化名称并去除(S)后缀 standardized_pos = position_part.split(' or ')[0].replace('(S)', '').strip() return standardized_pos, count
2. 处理整个DataFrame
遍历Positions列的每个字符串,拆分后应用标准化函数,生成结构化数据:
# 初始化结果存储列表 processed_data = [] for idx, row in df1.iterrows(): location = row['Location'] positions_str = row['Positions'] # 拆分职位条目并过滤空内容 position_items = [p.strip() for p in positions_str.split(',') if p.strip()] for item in position_items: pos_name, pos_count = standardize_position(item) processed_data.append({ 'Location': location, 'Standardized_Position': pos_name, 'Demand_Count': pos_count }) # 转换为结构化DataFrame processed_df = pd.DataFrame(processed_data)
3. 提取指定职位(以PayRoll_Manager为例)
直接过滤结构化后的DataFrame即可:
target_position = 'PayRoll_Manager' target_df = processed_df[processed_df['Standardized_Position'] == target_position] # 打印结果示例 print(target_df)
结果说明
- 标准化后的
processed_df包含三列:Location(地点)、Standardized_Position(统一后的职位名)、Demand_Count(需求人数) or连接的职位会自动合并为同一名称(如Auditor or Auditor(S)变为Auditor)- 带数字前缀的职位可正确提取人数(如
2 Brand_Manager的Demand_Count为2) - 筛选指定职位后的数据可直接用于后续与员工技能数据集的匹配操作
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

