【问题标题】:Copying the column index of csv file复制csv文件的列索引
【发布时间】:2014-02-26 08:47:30
【问题描述】:

我有一个 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

我想在每个Software Engineering ,Systems Software ,Operating Systems ,Database Management Systems ,Computer Networks I ,Formal Languages & Automata Theory ,Database Applications Laboratory ,Systems Software & Operating Systems Lab之后复制External,Internal,Total,Result

意思是它应该结束

 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 文件的其余部分。

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

【问题讨论】:

  • 你能举个例子说明你想要达到的目标吗,我认为你的意思不清楚......
  • 用我想要实现的输出编辑了问题
  • 问题不清楚。如果你想把它写在 csv 的第一行然后做一个列表并尝试 csvwriter.writerow([yourlist])

标签: python-2.7 csv pandas


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 2016-07-05
    • 2022-08-11
    • 2017-04-17
    • 2015-08-12
    • 2016-11-12
    • 2021-10-13
    • 2014-02-14
    • 2016-10-21
    • 1970-01-01
    相关资源
    最近更新 更多