[英]Python CSV transpose data in one column to rows
我有一個CSV文件,僅在第一列中包含數據,
我想使用python將每4行轉置到另一個空的CSV文件 ,例如,將第1行到第4行轉置到第一行; 然后將第5行到第8行轉換為第二行,...等等,最后我們可以在CSV文件中獲得5 * 4矩陣。
如何編寫腳本來做到這一點?請給我任何提示和建議,謝謝。
我正在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文件是
結果是
這不是我想要的。
您可以像這樣使用列表理解
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")
您可以像這樣使用List理解和雙循環。
>>> 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]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.