0

I have filea.csv and fileb.csv and I want to make filec.csv. filea has three columns of data:

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 has two columns of data, with matching values for row[0] of filea, but fewer rows:

date,PVkW,TBLkW
2014/12/26 16:00,108.95
2014/12/26 17:00,1.84
2014/12/26 18:00,0.0

For filec, I am trying to replace row[1] in filea with that of fileb when they have the same row[0], and otherwise just write filea's row in filec:

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

Here's what I am working with, adapted from 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)

When I run it (python3), I get the following error:

row[1] = b_dict[row[1]]
KeyError: '0'

How might I produce filec from filea and fileb as described?

interwebjill
  • 920
  • 13
  • 38

1 Answers1

0

It looks like the way you are referencing the key in b_dict in the line row[1] = b_dict[row[1]] is wrong, it should be row[1] = b_dict[row[0]], since row[0] is the key of the dictionary, not row[1].

Asif Iqbal
  • 4,562
  • 5
  • 27
  • 31