如何在csv文件中透视数据? [英] How to pivot data in a csv file?
本文介绍了如何在csv文件中透视数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我想转换:
Name,Time,Score
Dan,68,20
Suse,42,40
Tracy,50,38
/ p>
Into:
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()
作为转置操作:
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屋!
查看全文