根据csv文件填充行

时间:2014-09-10 14:17:07

标签: python csv

这是我想用python更新的csv文件。 它有3列:

col1 = [1,2,3,4,5,6,7,8,9,10] 
col2 = [A, A, A, B, C, C, C, C, A, A] 
col3 = []

对于col3中的每个单元格,我想填写一个只有当col2的内容发生变化时才会改变的id号。

在我的例子中,我会得到col3 = [1,1,1,2,3,3,3,3,4,4]

有人给我指路吗?

1 个答案:

答案 0 :(得分:2)

在Python 3中:

from itertools import groupby
from operator import itemgetter
import csv

with open('f1.csv', newline='') as f_in, open('f2.csv', 'w', newline='') as f_out:
    reader = csv.reader(f_in)
    writer = csv.writer(f_out)
    for i, (key, group) in enumerate(groupby(reader, key=itemgetter(1)), start=1):
        for row in group:
            writer.writerow(row + [i])

如果使用Python 2.7,请将with语句更改为

with open('f1.csv', 'rb') as f_in, open('f2.csv', 'wb') as f_out: