简体   繁体   English

在python中转置csv文件

[英]Transpose csv file in python

I'm new in python and I would like to transpose CSV files. 我是python的新手,我想转置CSV文件。

My csv: 我的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. 提前致谢。

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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM