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

标签 python csv matrix transpose

我有一个只包含第一列数据的 CSV 文件,

enter image description here

我想使用python将每4行转置到另一个空的CSV文件,例如第1行到第4行转置到第一行;然后将第 5 行到第 8 行转置到第二行,...等等,最后我们可以在 CSV 文件中得到一个 5 * 4 的矩阵。

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

这不是我想要的。

最佳答案

你可以像这样使用列表理解

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")

关于Python CSV 将一列中的数据转置为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23214814/

相关文章:

Python 将 CSV 转换为列表字典

php - 添加 mysql 列以在 csv php 中输出?

java - 在 ","上 split ,但不在 "\,"上 split

matlab - 用循环 block 对 block 循环矩阵进行对角化

c++ - 编译时模板值推导

python - 处理大文件的最佳 Python Zip 模块是什么?

python - 以 3 为一组打印 python 列表

python - 如何将不确定性表达式(例如 3.23 +/- 0.01)从字符串转换为 float ?

c - 警告:从不兼容的指针类型传递''的参数1 [默认启用]

python - 为什么我的函数检查英语应用程序对非英语应用程序返回 True?