我有類似結構的相當大的逗號分隔 csv文件到:移調CSV同時保持ID
ZipCd Var1 Var2 Var 3
12345 12 45 10
67890 13 23 5
. . . .
. . . .
. . . .
30010 99 17 6
對於每個ZipCd有許多變量會向右(約250總變量)。我想對於要產生以下的輸出:
ZipCd Var Value
12345 1 12
12345 2 45
12345 3 10
67890 1 13
67890 2 23
67890 3 5
30010 1 99
30010 2 17
30010 3 6
我已經嘗試以下操作:
with open("file.csv") as f, open("out.csv","w") as out:
headers = next(f).split()[0:] #Get first row of original csv for headers and variable names
for row in f:
row = row.split(",") #split row into values delimitted by comma
ZipCd = row[0]
Var1 = row[1]
Var2 = row[2]
Var3 = row[3]
data = zip(headers, row[1:])
for a, b in data:
out.write("{} {} {}\n".format(ZipCd,a,b))
和產生:
12345 ZipCd,Var1,Var2,Var3 12
67890 ZipCd,Var1,Var2,Var3 13
生產所需的輸出任何幫助不勝感激。
我不明白:是你的輸入文件逗號分隔或空格分隔? –
逗號,對不起。應該更加明確。 – Daniel
我從你得到的錯誤中猜出它! –