Python csv:合并具有相同字段的行

时间:2016-11-15 22:07:15

标签: python csv

我试图将几行csv数据合并为一个长行,因为两个单元格包含相同的数据。例如,请使用以下csv:

one, two, three
1, 2, 3
4, 5, 6
7, 8, 9
1, 1, 1
4, 4, 4

如果两行在第[0]行共享相同的值,我希望第二行附加到第一行。所以我的最终产品应该是这样的:

one, two, three
1, 2, 3, 1, 1, 1
4, 5, 6, 4, 4, 4
7, 8, 9

到目前为止,这是我的尝试:

import csv

uniqueNum = []
uniqueMaster = []
count = -1
with open("Test.csv", "rb") as source:
    reader = csv.reader(source)
    header = next(reader)
    for row in reader:
        if row[0] not in uniqueNum:
            uniqueMaster.append(row)
            uniqueNum.append(row[0])
            count = count + 1
            for row in reader:
                if row[0] in uniqueNum:
                    uniqueMaster[count].append(row)

with open("holding.csv","wb") as result:
    writer = csv.writer(result)
    writer.writerow(header)
    for row in uniqueMaster:
        writer.writerow(row) 

事情对我来说很好,但我的脚本只输出以下内容:

one, two, three
1, 2, 3, ['1', '1', '1']

由于两个原因,这显然是错误的。首先,它不会遍历整个csv,其次,附加的值被挤压到一个单元格而不是单个单元格中。如果有人对这项工作有任何建议,我会非常感激!

2 个答案:

答案 0 :(得分:2)

请改用词典。从代码中间开始(假设我已经声明了一个名为my_dict的dict):

 for row in reader:
    if row[0] in my_dict.keys():
       my_dict[row[0]].extend(row)
    else:
       my_dict[row[0]]=row
  #...now we are at the bottom of your code, writing to the csv
 for v in my_dict.values():
    writer.writerow(v)

答案 1 :(得分:1)

- name: resource-docker
  type: git
  source:
    uri: https://github.com/$MYUSER/$MYREPO.git
    branch: master
    paths:
      - <path/to/Dockerfile/or/whatever>
      - <path/to/other/triggering/diffs>