如何在DataFrame中新增列存放同公司同年份其他工作室的员工名单
Pandas 实现方案
实现思路
- 核心逻辑是按年份、公司ID两个字段分组,确保只统计同一年、同一公司下的其他工作室数据
- 分组后过滤掉当前行对应的工作室,拼接剩余所有工作室的
employees字段值即可 - 两种实现方式,小数据量用第一种写法更简洁,大数据量用第二种性能更高
代码实现
方式1:分组自定义函数(适合小数据量)
import pandas as pd def calc_other_emp(group): other_emp_list = [] for _, row in group.iterrows(): # 筛选同组非当前工作室的员工,逗号拼接 current_other = group[group['studio_id'] != row['studio_id']]['employees'].str.cat(sep=',') other_emp_list.append(current_other) group['other_studio_emp'] = other_emp_list return group # 分组应用函数,生成新字段 df = df.groupby(['year', 'company_id'], group_keys=False).apply(calc_other_emp)
方式2:预聚合关联(适合大数据量,避免逐行迭代性能问题)
# 预聚合同公司同年的所有工作室ID和员工列表 group_agg = df.groupby(['year', 'company_id']).agg( studio_list = ('studio_id', list), emp_list = ('employees', list) ).reset_index() # 聚合结果关联回原表 df = df.merge(group_agg, on=['year', 'company_id'], how='left') # 过滤当前工作室后拼接员工 df['other_studio_emp'] = df.apply( lambda x: ','.join([emp for idx, emp in enumerate(x['emp_list']) if x['studio_list'][idx] != x['studio_id']]), axis=1 ) # 清理临时生成的辅助字段 df = df.drop(columns=['studio_list', 'emp_list'])
补充说明
- 若需要对最终拼接的员工去重,可在拼接逻辑后增加去重处理,示例:
# 去重示例(以方式1的拼接逻辑为例) current_other = ','.join(set(current_other.split(','))) if current_other else ''
- 若同公司同年只有1个工作室,生成的
other_studio_emp会自动为空字符串,符合业务逻辑。
内容的提问来源于stack exchange,提问作者reresearchgames
相关产品推荐
相关产品推荐

