Created
July 16, 2012 19:15
-
-
Save kojiromike/3124458 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from itertools import chain, groupby | |
from csv import reader, writer | |
with open('foo.csv') as infile: | |
r = reader(infile) | |
groups = groupby(r, lambda x:x[0]) # Group by the first column | |
lines = [] | |
for group in groups: | |
gchain = chain(g[1:] for g in group[1]) # [[400, 1, 2, 3], [400, 4,5,6] -> [1,2,3,4,5,6] | |
lines.append([group[0]] + list(gchain)) # [[400, 1,2,3,4,5,6], [410, a,b,c,d,e,f,g], …] | |
with open('bar.csv') as outfile: | |
w = writer(outfile) | |
w.writelines(zip(*lines)) # Transpose all the lines and return an iterable to write |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment