Python将CSV中一列的数据转置为多行

2 投票
2 回答
2168 浏览
提问于 2025-04-18 03:42

我有一个CSV文件,里面只有第一列有数据,

enter image description here

我想用Python把每4行数据转置到另一个空的CSV文件里,比如说,把第1到第4行的数据转置到新文件的第一行;然后把第5到第8行的数据转置到第二行,依此类推,最后我们能得到一个5行4列的矩阵在CSV文件里。

enter image description here

我该怎么写一个脚本来实现这个呢?请给我一些提示和建议,谢谢。

我在Windows 8.1 x64上使用的是Python 2.7.4。


更新#1

我使用了thefortheye提供的以下代码,

import sys, os
os.chdir('C:\Users\Heinz\Desktop')
print os.getcwd()

from itertools import islice
with open("test_csv.csv") as in_f, open("Output.csv", "w") as out_file:
    for line in ([i.rstrip()] + map(str.rstrip, islice(in_f, 3)) for i in in_f):
        out_file.write("\t".join(line) + "\n")

输入的CSV文件是,

enter image description here

而结果是,

enter image description here

这并不是我想要的结果。

2 个回答

0

你可以像这样使用列表推导和双重循环。

>>> M = 3
>>> N = 5
>>> a = range(M * N)
>>> o = [[a[i * N + j] for j in xrange(N)] for i in xrange(M)]
>>> print o
[[ 0,  1,  2,  3,  4],
 [ 5,  6,  7,  8,  9],
 [10, 11, 12, 13, 14]]
1

你可以这样使用列表推导式

data = range(20)
print data
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
print[data[i:i + 4] for i in xrange(0, len(data), 4)]
# [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18,19]]

你可能想用 56 代替 4

因为你打算从文件中读取内容,你可以这样做

from itertools import islice
with open("Input.txt") as in_file:
    print [[int(line)] + map(int, islice(in_file, 3)) for line in in_file]

编辑 根据更新后的问题,

from itertools import islice
with open("Input.txt") as in_f, open("Output.txt", "w") as out_file:
    for line in ([i.rstrip()] + map(str.rstrip, islice(in_f, 3)) for i in in_f):
        out_file.write("\t".join(line) + "\n")

编辑: 既然你想要用逗号分隔的值,你可以用 , 把行连接起来,像这样

        out_file.write(",".join(line) + "\n")

撰写回答