简体   繁体   English

将python列表作为新列添加到csv文件

[英]Adding python lists as new columns to a csv file

I have a csv file that contains five columns: 我有一个包含五列的csv文件:

a1 b1 c1 d1 e1
a2 b2 c2 d2 e2
a3 b3 c3 d3 e3

And I have some lists that I want to add to this csv (each list as a new column), so the end result would look something like this: 我有一些要添加到此csv的列表(每个列表都作为新列),因此最终结果将如下所示:

a1 b1 c1 d1 e1 f1 g1 h1
a2 b2 c2 d2 e2 f2 g2 h2
a3 b3 c3 d3 e3 f3 g3 h3

I can save these lists as a new csv 我可以将这些列表另存为新的csv

outputdata=zip(list1,list2,list3,list4)
writer=CsvUnicodeWriter(open("myoutput.csv","wb"))
writer.writerows(output data)

But this is not exactly what I need. 但这不是我真正需要的。 Thanks in advance. 提前致谢。

The index of the source csv and the zipped lists should match so you can use enumerate to track it. 源csv的索引和压缩列表应匹配,以便您可以使用enumerate进行跟踪。

zipped = zip(list1, list2, list3, list4)

with open('in.csv', 'rb') as infile, open('out.csv' 'wb') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    for i, row in enumerate(reader):
        row.extend(zipped[i])
        writer.writerow(row)

If you are doing a lot of data wrangling like this however check out the pandas library. 如果您正在像这样处理大量数据,请查看pandas库。 The pandas code is a bit simpler, although you have to get used to the pandas api, which is based on index labels and vectorised operations. 尽管您必须习惯基于索引标签和向量化操作的pandas api,但pandas代码要简单一些。

indata = pd.read_csv('in.csv')
zipped = pd.DataFrame(zip(List1, List2, List3, List4)
#axis=1 indicates to concat the frames column wise
outdata = pd.concat([indata, zipped], axis=1)
#we dont want headers and dont want the row labels
outdata.to_csv('out.csv', header=False, index=False)

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

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