python用另一个csv中的相邻列数据替换一个csv中的相邻列部分

2024-04-24 19:39:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有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


Tags: csv数据indateopencontentdictrow