如何转置 csv 文件中的数据集? [英] How to transpose a dataset in a csv file?

查看:92
本文介绍了如何转置 csv 文件中的数据集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想转换:

Name,Time,Score
Dan,68,20
Suse,42,40
Tracy,50,38

进入:

Name,Dan,Suse,Tracy
Time,68,42,50
Score,20,40,38

原始问题错误地使用了转置"一词.

the original question used the term "transpose" incorrectly.

推荐答案

如果整个文件内容适合内存,则可以使用

If the whole file contents fits into memory, you can use

import csv
from itertools import izip
a = izip(*csv.reader(open("input.csv", "rb")))
csv.writer(open("output.csv", "wb")).writerows(a)

你基本上可以把zip()izip()看作是转置操作:

You can basically think of zip() and izip() as transpose operations:

a = [(1, 2, 3),
     (4, 5, 6),
     (7, 8, 9)]
zip(*a)
# [(1, 4, 7),
#  (2, 5, 8),
#  (3, 6, 9)]

izip() 避免了立即复制数据,但基本上会做同样的事情.

izip() avoids the immediate copying of the data, but will basically do the same.

这篇关于如何转置 csv 文件中的数据集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆