我正在尝试为下面的代码添加一个功能,但似乎在某处弄乱了。
以下代码基本上为以下每个扬声器重复第一个“z”表列(如excel转置)。对于这些列,“z”之后是日期,只需要一个日期列。
问题是python脚本正确生成了值,但是需要插入列来讨论该日期,将这些信息重复到日期的所有值。
Python脚本:
from itertools chain from import
f = open ("C:\\Test.CSV", "r")
sep = ""
M = []
M = [M + [s.strip () for s in line.split (sep)] for line in f.readlines ()]
f.close ()
i = 0 # title
w = 4 # cols in title
r = 1 # body
z = 4 # fields fix
result = [M [i] [w] + ["date"] + ["Value"]] + list (chain (* [[x [: z] + [y] for y in x [z + 1: ]] for x in M [A:]]))
f = open ("C:\out.csv", 'w')
f.writelines ("\ n" .join ("". join (s) for s in result) + "\ 0")
f.close ()
东西(输入):
[[X; y; date1; date2; date3]
[01; 02; 03; 04; 05]
[06; 07; 08; 09; 10]
[11; 12; 13, 14 15]]
当前脚本正确执行此操作(现在输出):
[[X; y; date1]
[01; 02; 03]
[01; 02; 04]
[01; 02; 05]
[06; 07; 08]
[06; 07; 09]
[06; 07; 10]
[11; 12; 13]
[11; 12; 14]
[11; 12; 15]]
我输出的是这个(所需的输出):
[[X; y; date; value; ]
[01; 02; date1; 03]
[01; 02; date2; 04]
[01; 02; date3; 05]
[06; 07; date1; 08]
[06; 07; date2; 09]
[06; 07; date3; 10]
[11; 12; date1; 13]
[11; 12; date2; 14]
[11; 12; date3; 15]]
有没有人这样做过?
答案 0 :(得分:0)
您有什么理由不能使用csv?
import csv
f = open("iter.csv", "r")
g = open("out.csv", "w", newline="")
transpose_columns = ['date1', 'date2', 'date3']
target_columns = ['date', 'value']
reader = csv.DictReader(f)
writer = csv.DictWriter(g, fieldnames=[a for a in reader.fieldnames
if a not in transpose_columns] + target_columns,
extrasaction='ignore')
writer.writeheader()
for row in reader:
for col in transpose_columns:
row[target_columns[0]] = col
row[target_columns[1]] = row[col]
writer.writerow(row)
f.close()
g.close()