不使用pandas,如何转换CSV指定行的特殊表头数据并导出
解决CSV表头结构化转换问题(无Pandas)
问题描述
我有一个CSV文件,第4行是表头、第5行是对应数据。表头格式示例如下:
Title_XYZ[0].XXX_YYY_Record.XXX_YYY.AAA Title_XYZ[0].XXX_YYY_Record.XXX_YYY.BBB Title_XYZ[1].XXX_YYY_Record.XXX_YYY.AAA Title_XYZ[1].XXX_YYY_Record.XXX_YYY.BBB
方括号内的数字会随单元格变化。需要将这些数据提取并转换为指定格式的新CSV文件,但不能使用Pandas。
原数据格式:
| Title_XYZ[0].XXX_YYY_Record.XXX_YYY.AAA | Title_XYZ[0].XXX_YYY_Record.XXX_YYY.BBB | Title_XYZ[1].XXX_YYY_Record.XXX_YYY.AAA | Title_XYZ[1].XXX_YYY_Record.XXX_YYY.BBB |
|---|---|---|---|
| 12 | 13 | 14 | 15 |
期望输出格式:
| AAA | BBB |
|---|---|
| 12 | 13 |
| 14 | 15 |
之前尝试用Python的csv模块读取文件,通过header = lines[4].split(',')获取数据并写入新CSV,但只能复制粘贴数据,无法实现AAA、BBB与对应数据的匹配转换。
实现思路
核心是解析每个表头的结构,提取两个关键信息:
- 方括号内的索引值(如
[0]中的0),用于分组同一组的AAA/BBB数据 - 表头最后一个字段(AAA/BBB),作为新表头
通过字典分组存储同一索引下的AAA和BBB数据,再按索引顺序生成新的CSV行。
代码实现
import csv # 原文件路径和新文件路径 input_file = "input.csv" output_file = "output.csv" # 读取文件,跳过前3行,获取表头(第4行)和数据行(第5行) with open(input_file, 'r', newline='', encoding='utf-8') as f: reader = csv.reader(f) # 跳过前3行 for _ in range(3): next(reader) # 获取表头和数据行 header_row = next(reader) data_row = next(reader) # 用字典分组数据:key是索引数字,value是{'AAA': 值, 'BBB': 值} grouped_data = {} for header, value in zip(header_row, data_row): # 拆分表头,提取索引和字段名 parts = header.split('.') # 从'Title_XYZ[0]'中提取括号内的数字 index_part = parts[0] index = int(index_part[index_part.find('[')+1 : index_part.find(']')]) # 提取最后一段作为字段名(AAA/BBB) field = parts[-1] # 初始化分组字典 if index not in grouped_data: grouped_data[index] = {} grouped_data[index][field] = value # 按索引排序,生成新的行 sorted_indices = sorted(grouped_data.keys()) new_rows = [] # 添加新表头 new_rows.append(['AAA', 'BBB']) # 按索引顺序添加数据行 for idx in sorted_indices: new_rows.append([grouped_data[idx]['AAA'], grouped_data[idx]['BBB']]) # 写入新CSV文件 with open(output_file, 'w', newline='', encoding='utf-8') as f: writer = csv.writer(f) writer.writerows(new_rows)
代码说明
- 文件读取:用
csv.reader读取文件,跳过前3行后获取表头和数据行,避免手动split处理逗号转义问题。 - 表头解析:通过字符串拆分和索引提取,从每个表头中分离出分组索引和字段名。
- 数据分组:用字典将同一索引下的AAA、BBB数据关联起来,确保数据对应正确。
- 排序与写入:按索引排序后,生成符合要求的新表头和数据行,写入新CSV文件。
内容的提问来源于stack exchange,提问作者a_44
相关产品推荐
相关产品推荐

