简体   繁体   English

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

[英]Adding another column to a CSV file w/ python

I am looking to add another column to a CSV file w/ python. 我想将另一列添加到带python的CSV文件中。

file1 is Date.csv has format file1是Date.csv具有格式

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

and

file2 is Price.csv file2是Price.csv

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

My desired output is (in Date.csv) 我想要的输出是(在Date.csv中)

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

but what I'm returning is the price repeating 但是我要返回的是重复的价格

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

My program is as follows 我的程序如下

import csv

with open('C:/Users/User/OneDrive/Documents/Price.csv','r') as csvinput:
    with open('C:/Users/User/OneDrive/Documents/Date.csv', 'w') as csvoutput:
        writer = csv.writer(csvoutput, lineterminator='\n')
        reader = csv.reader(csvinput)

        all = []
        row = next(reader)

        for row in reader:
            row.append(row[1])
            all.append(row)

        writer.writerows(all)

Appreciate some guidance, cheers 赞赏一些指导,欢呼

You need 3 files at the same time, and append only needed column from second file 您同时需要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]])

And the output: 并输出:

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

You can't just write a single column into an existing file. 您不能只将一列写入现有文件。 Best option is create a new file. 最好的选择是创建一个新文件。 If the data is in order for both files then you can simply zip them up and write the updated dictionary out: 如果数据符合两个文件的顺序,则只需将它们压缩并写出更新的字典即​​可:

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)

Pandas is also a another option: 熊猫也是另一个选择:

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')

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM