我有filea.csv和fileb.csv,我想做filec.csv。filea有三列数据:
date,PVkW,TBLkW
2014/12/26 16:00,20.0,307.4633
2014/12/26 17:00,0.0,291.6297
2014/12/26 18:00,0.0,240.87265
2014/12/26 19:00,0.0,251.475
2014/12/26 20:00,0.0,291.81406
2014/12/26 21:00,0.0,268.26328
2014/12/26 22:00,0.0,257.0367
fileb有两列数据,与filea的第[0]行的值匹配,但行数较少:
date,PVkW,TBLkW
2014/12/26 16:00,108.95
2014/12/26 17:00,1.84
2014/12/26 18:00,0.0
对于filec,当filea中的行[1]与fileb中的行[0]相同时,我尝试将它们替换为fileb中的行[1],否则只需在filec中写入filea的行:
date,PVkW,TBLkW
2014/12/26 16:00,108.95,307.4633
2014/12/26 17:00,1.84,291.6297
2014/12/26 18:00,0.0,240.87265
2014/12/26 19:00,0.0,251.475
2014/12/26 20:00,0.0,291.81406
2014/12/26 21:00,0.0,268.26328
2014/12/26 22:00,0.0,257.0367
以下是我的作品,改编自python update a column value of a csv file according to another csv file
import csv
filea = "filea.csv"
fileb = "fileb.csv"
filec = "filec.csv"
delim = ","
a_content = csv.reader(open(filea,"r"), delimiter=delim)
b_content = csv.reader(open(fileb,"r"), delimiter=delim)
datawriter = csv.writer(open(filec, "w"), delimiter=delim)
b_dict = {}
next(b_content)
for row in b_content:
b_dict[row[0]] = row[1]
for row in a_content:
if row[0] in b_dict:
row[1] = b_dict[row[1]]
datawriter.writerow(row)
当我运行它(python3)时,会出现以下错误:
row[1] = b_dict[row[1]]
KeyError: '0'
如何从filea和fileb生成filec
看起来您在
row[1] = b_dict[row[1]]
行中引用b_dict
中的键的方式是错误的,应该是row[1] = b_dict[row[0]]
,因为row[0]
是字典的键,而不是row[1]
相关问题 更多 >
编程相关推荐