使用python将另一列添加到CSV文件

时间:2016-01-26 01:52:30

标签: python python-2.7 csv python-2.x

我希望将另一列添加到带有python的CSV文件中。

file1是Date.csv具有格式

x = ActionController::Base.new.render_to_string( 
            template: "my_module/my_view_template", 
            locals: { my_var: in_my_var})

file2是Price.csv

ID, Date
0,"Jan 22, 2016"
1,"Jan 21, 2016"
2,"Jan 20, 2016"
3,"Jan 19, 2016"

我想要的输出是(在Date.csv中)

ID, Price
0,27.89
1,26.80
2,26.78
3,26.00

但我要归还的是价格重复

ID, Date
0,"Jan 22, 2016", 27.89
1, "Jan 21, 2016", 26.80
2, "Jan 20, 2016", 26.78
3, "Jan 19, 2016", 26.00

我的程序如下

0,27.89,27.89
1,26.80,26.80
2,26.78,26.78
3,26.00,26.00

欣赏一些指导,欢呼

2 个答案:

答案 0 :(得分:3)

您需要同时拥有3个文件,并且只附加第二个文件所需的列

import csv

date_reader = csv.reader(open('Date.csv', 'rb'))
price_reader = csv.reader(open('Price.csv', 'rb'))
writer = csv.writer(open('NewData.csv', 'wb'))
for date_row in date_reader:
    price_row = price_reader.next()
    writer.writerow(date_row + [price_row[1]])

输出:

ID, Date, Price
0,"Jan 22, 2016",27.89
1,"Jan 21, 2016",26.80
2,"Jan 20, 2016",26.78
3,"Jan 19, 2016",26.00

答案 1 :(得分:3)

您不能只将一列写入现有文件。最好的选择是创建一个新文件。如果数据是为了两个文件的顺序,那么你可以简单地将它们压缩并写出更新的字典:

with open('C:/Users/User/OneDrive/Documents/Date.csv') as file1, \
     open('C:/Users/User/OneDrive/Documents/Price.csv') as file2, \
     open('C:/Users/User/OneDrive/Documents/Output.csv', 'w') as output:
    reader1 = csv.DictReader(file1)
    reader2 = csv.DictReader(file2)
    writer = csv.DictWriter(output, ['ID', 'Date', 'Price'])
    writer.writeheader()  # Optional if you want the header

    for row1, row2 in zip(reader1, reader2):
        row1.update(row2)
        writer.writerow(row1)

熊猫也是另一种选择:

import pandas as pd
file1 = pd.read_csv('Data.csv', index_col='ID')
file2 = pd.read_csv('Price.csv', index_col='ID')
pd.concat([file1,file2], axis=1).to_csv('Output.csv')

输出:

ID,Date,Price
0,"Jan 22, 2016",27.89
1,"Jan 21, 2016",26.80
2,"Jan 20, 2016",26.78
3,"Jan 19, 2016",26.00