如何在Python中转置表格型组织层级数据以展示下属信息?
问题描述
我有一个CSV数据集,结构如下:
| Employee | Manager |
|---|---|
| A | B |
| B | E |
| C | E |
| D | B |
| E | H |
| F | H |
| G | H |
| H |
需要将其转换为列出每位员工下属的表格,转换后格式如下:
| Employee | Manager | Report 1 | Report 2 | Report 3 |
|---|---|---|---|---|
| A | B | |||
| B | E | A | D | |
| C | E | |||
| D | B | |||
| E | H | B | C | |
| F | H | |||
| G | H | |||
| H | E | F | G |
解决方案(Python实现)
可以用pandas库快速完成这个转换,步骤如下:
1. 读取CSV数据
先读取原始CSV文件,处理可能的空值:
import pandas as pd # 读取CSV文件,替换成你的文件路径 df = pd.read_csv('employees.csv') # 将Manager列的空值转为空字符串(可选,根据需求调整) df['Manager'] = df['Manager'].fillna('')
2. 构建经理-下属映射
通过分组收集每个经理对应的下属列表:
# 按Manager分组,把对应的Employee整理成下属列表 manager_reports = df.groupby('Manager')['Employee'].apply(list).to_dict() # 给没有下属的员工补充空列表 for emp in df['Employee']: if emp not in manager_reports: manager_reports[emp] = []
3. 确定下属列数量
找到所有经理中最多的下属数,生成对应的Report N列名:
max_reports = max(len(reports) for reports in manager_reports.values()) report_columns = [f'Report {i+1}' for i in range(max_reports)]
4. 拆分下属到对应列
为每个员工生成对齐的下属列表,长度不足的用空字符串填充:
def split_reports(employee): reports = manager_reports.get(employee, []) # 补全到最大下属数的长度 return reports + [''] * (max_reports - len(reports)) # 生成下属列的DataFrame reports_df = pd.DataFrame(df['Employee'].apply(split_reports).tolist(), columns=report_columns)
5. 合并数据并输出
把原始数据和下属列合并,得到最终结果:
# 合并两个DataFrame final_df = pd.concat([df, reports_df], axis=1) # 打印结果到控制台 print(final_df) # 保存为新的CSV文件 final_df.to_csv('employees_with_reports.csv', index=False)
运行后得到的结果会和目标表格完全匹配,没有下属的员工对应列会显示空字符串。
内容的提问来源于stack exchange,提问作者harcot
相关产品推荐
相关产品推荐

