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

查看:619
本文介绍了如何在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天全站免登陆