求Python或Git Bash方案:找出同时就读两所院校的人员
问题描述
我有一个CSV文件,数据结构如下:
| Harvard | MIT |
|---|---|
| David | Troy |
| Siri | Charlie |
| Troy | David |
| Alexa | Cortana |
| Cortana | Man |
| Animal | David |
需要生成新增Output列的结果,Output列仅包含同时出现在Harvard和MIT列中的人员,顺序无要求,最终结果格式如下:
| Harvard | MIT | Output |
|---|---|---|
| David | Troy | David |
| Harvard | MIT | Troy |
| David | Troy | Cortana |
| Siri | Charlie | |
| Troy | David | |
| Alexa | Cortana | |
| Cortana | Man |
Python 实现方案
代码示例
import csv # 读取原始CSV,提取两列人员数据 harvard = [] mit = [] with open('input.csv', 'r', newline='', encoding='utf-8') as f: reader = csv.DictReader(f) for row in reader: harvard.append(row['Harvard'].strip()) mit.append(row['MIT'].strip()) # 计算同时出现的人员交集 common_people = list(set(harvard) & set(mit)) # 生成带Output列的新CSV with open('input.csv', 'r', newline='', encoding='utf-8') as infile, \ open('output.csv', 'w', newline='', encoding='utf-8') as outfile: reader = csv.DictReader(infile) fieldnames = reader.fieldnames + ['Output'] writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() # 先写入交集人员对应的行 for person in common_people: writer.writerow({'Harvard': '', 'MIT': '', 'Output': person}) # 再写入原始数据行,Output列留空 for row in reader: row['Output'] = '' writer.writerow(row)
使用说明
- 将原始数据保存为
input.csv - 运行代码后,生成的
output.csv即为目标结果
Git Bash(Windows)实现方案
命令示例
# 提取Harvard列去重 cut -d ',' -f1 input.csv | tail -n +2 | sort | uniq > harvard.txt # 提取MIT列去重 cut -d ',' -f2 input.csv | tail -n +2 | sort | uniq > mit.txt # 找出两列人员的交集 comm -12 <(sort harvard.txt) <(sort mit.txt) > common.txt # 生成带Output列的表头 head -n1 input.csv | sed 's/$/,Output/' > output.csv # 追加交集人员对应的空行列 while read name; do echo ",,$name"; done < common.txt >> output.csv # 追加原始数据行,末尾补空Output列 tail -n +2 input.csv | sed 's/$/,/' >> output.csv
使用说明
- 确保原始CSV文件名为
input.csv,放在当前目录 - 在Git Bash中依次执行命令,最终生成
output.csv
内容的提问来源于stack exchange,提问作者Prabesh Aryal
相关产品推荐
相关产品推荐

