使用Python累加CSV文件数据遇NameError,求代码修正及格式输出方案
解决CSV数据匹配累加并生成矩阵表格的问题
首先,咱们先看你遇到的NameError——虽然从你贴的代码来看,x在for x in keys循环里是应该被定义的,可能是复制代码时行号标注错了?不过没关系,咱们重点放在实现你需要的矩阵表格需求上,顺便把代码里的逻辑问题一起修正。
问题分析
你的需求核心是:
- 对CSV中
out_gate到in_gate的组合累加n_con的值 - 生成一个行列分别为所有
out_gate和指定in_gate(a/b/c/d)的矩阵,没有数据的组合填0 - 最终可以导出为Excel兼容的CSV文件
修正后的完整代码
import csv from collections import defaultdict # 定义所有需要的目标列(in_gate的可能值,包括示例里的d) target_in_gates = ['a', 'b', 'c', 'd'] # 初始化嵌套字典,默认值为0 accumulated_data = defaultdict(lambda: defaultdict(int)) # 读取CSV文件(注意你的文件是txt后缀但实际是CSV格式) with open("C:/Users/user/test1.txt", newline='') as in_file: csv_reader = csv.reader(in_file) # 跳过表头 next(csv_reader) for row in csv_reader: # 确保行数据足够长,避免索引错误 if len(row) >= 3: out_gate, in_gate, count = row # 累加对应组合的数值 accumulated_data[out_gate][in_gate] += int(count) # 获取所有唯一的out_gate并排序 sorted_out_gates = sorted(accumulated_data.keys()) # 准备写入CSV的数据:先写表头 output_rows = [[''] + target_in_gates] # 填充每一行的数据 for out_gate in sorted_out_gates: row_data = [out_gate] for in_gate in target_in_gates: # 取出累加值,没有的话默认0 row_data.append(accumulated_data[out_gate][in_gate]) output_rows.append(row_data) # 写入到输出CSV文件(可以直接用Excel打开) with open("C:/Users/user/result_matrix.csv", 'w', newline='') as out_file: csv_writer = csv.writer(out_file) csv_writer.writerows(output_rows) # 打印预览结果 print("生成的矩阵预览:") for row in output_rows: print(row)
代码说明
- 目标列定义:明确指定了
target_in_gates为['a','b','c','d'],确保即使原数据里没有d作为in_gate的情况,也会在矩阵里生成对应的列并填0。 - 数据累加:用
defaultdict自动处理不存在的组合,默认值为0,避免键不存在的错误。 - 矩阵构建:先构建表头(空单元格+目标列),然后遍历每个
out_gate,依次取出对应每个in_gate的累加值,组成一行数据。 - CSV写入:用
csv.writer把矩阵数据写入新的CSV文件,直接可以用Excel打开查看。
运行结果
根据你提供的示例数据,生成的CSV内容会是:
,a,b,c,d /a_a,0,4,0,0 /a_b,2,0,4,0 /a_c,9,8,0,0 /a_d,0,2,5,0
完全符合你需要的表格格式,其中/a_c->a的累加值是5+4=9,/a_c->b是5+3=8,和你的示例预期一致,同时d列全部为0。
内容的提问来源于stack exchange,提问作者kts
相关产品推荐
相关产品推荐

