复制csv文件的列索引

时间:2014-02-26 08:47:31

标签: python-2.7 csv pandas

我有一个csv文件,我使用python从html文档解析,第一行如下:

Subject,External,Internal,Total,Result,Software Engineering ,Systems Software ,Operating Systems ,Database Management Systems ,Computer Networks  I ,Formal Languages & Automata Theory ,Database Applications Laboratory ,Systems Software & Operating Systems Lab. ,Total Marks

我希望在每个External,Internal,Total,Result

之后复制Software Engineering ,Systems Software ,Operating Systems ,Database Management Systems ,Computer Networks I ,Formal Languages & Automata Theory ,Database Applications Laboratory ,Systems Software & Operating Systems Lab

意味着它应该以

结尾
 Subject ,Software Engineering,External,Internal,Total,Result ,Systems Software,External,Internal,Total,Result ,Operating Systems,External,Internal,Total,Result ,Database Management Systems,External,Internal,Total,Result ,Computer Networks  I,External,Internal,Total,Result ,Formal Languages & Automata Theory,External,Internal,Total,Result ,Database Applications Laboratory,External,Internal,Total,Result ,Systems Software & Operating Systems Lab,External,Internal,Total,Result

这将构成我的csv文件的第一行。 我有另一段代码将填满其余的csv文件。

实现这一目标的简单方法是什么?

1 个答案:

答案 0 :(得分:2)

import csv
with open('headers.csv', 'rb') as csvfile:
   header_reader = csv.reader(csvfile)
   headers = header_reader[0]
#You now have the headers from the first line of the CSV
#Extract the headers you want to repeat
repeat_headers = headers[1:5]  #contains [External,Internal,Total,Result]

#Build new list
new_headers = [headers[0]] + repeat_headers   #Your first element is at position 0
for i in xrange(5, len(headers)):             #Your remaining elements start at position 5
   new_headers.append(headers[i])
   new_headers += repeat_headers