【问题标题】:python replace adjacent part of a column in one csv with adjacent column data from another csvpython用另一个csv中的相邻列数据替换一个csv中列的相邻部分
【发布时间】:2018-02-24 06:53:58
【问题描述】:

我有 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 的 row[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,当它们具有相同的row[0]时,我试图将filea中的row[1]替换为fileb的row[1],否则只需将filea的行写入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

这是我正在使用的内容,改编自 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?

【问题讨论】:

    标签: python csv


    【解决方案1】:

    看起来您在row[1] = b_dict[row[1]] 行中引用b_dict 中的键的方式是错误的,它应该是row[1] = b_dict[row[0]],因为row[0] 是字典的键,而不是row[1]

    【讨论】:

    • 你是对的。我犯了一个愚蠢的错误,但希望这可以作为其他人的榜样。谢谢。
    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 2017-09-27
    • 2023-03-16
    • 2017-04-22
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多