0

I'm new in python and I would like to transpose CSV files.

My csv:

sphere,product
-9.00,COA-91391
-9.50,COA-91391
+0.50,COA-91392
+0.75,COA-91392
+1.00,COA-91392

The output I wish:

COA-91391,-9.00,-9.50
COA-91392,+0.50,+0.75,+1.00

If someone can give me some help on how to proceed.

Thanks in advance.

smottt
  • 3,272
  • 11
  • 37
  • 44
  • 1
    What have you tried ? Do have trouble reading the file, reordering data, printing it ? – Mel Dec 11 '15 at 09:05
  • First read Python doc for csv module, then look for the built in function zip. Merge all together and feel free to ask here if you are stuck. – Serge Ballesta Dec 11 '15 at 09:16
  • It's not a transpose at all. It's a "group by" operation you ask for. Consider sorting and using `itertools.groupby` https://docs.python.org/3/library/itertools.html?highlight=itertools#itertools.groupby or to install and use `pandas`. – Lærne Dec 11 '15 at 09:21

1 Answers1

1
with open('data.csv') as f:
    lines = f.readlines()

lines = lines[1:] # skip header
result = dict()
for line in lines:
    sphere, product = line.split(',')
    product = product.strip()
    if not result.has_key(product):
        result[product] = list()
    result[product].append(sphere.strip())

with open('data_out.csv', 'w') as f:
    for product, spheres_list in result.items():
        f.write("%s,%s\n" %(product, ','.join(spheres_list)))
Roman
  • 515
  • 5
  • 16