且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在CSV文件中转置数据集?

更新时间:2023-11-18 22:48:04

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

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.