Skip to content

Instantly share code, notes, and snippets.

@kojiromike
Created July 16, 2012 19:15
Show Gist options
  • Save kojiromike/3124458 to your computer and use it in GitHub Desktop.
Save kojiromike/3124458 to your computer and use it in GitHub Desktop.
#!/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