我的数据如下所示
id,Stage1Pow1,Stage1Pow2,Stage2Pow1,Stage2Pow2
A,1.0,1.5,1.1,1.4
B,0.9,1.2,0.9,1.1
C,1.0,1.0,0.8,0.8
如何将它们转换为以下格式,以便按阶段存储和进一步分析。
id,StageNo,Pow1,Pow2
A,s1,1.0,1.5
A,s2,1.1,1.4
B,s1,0.9,1.2
B,s2,0.9,1.1
C,s1,1.0,1.0
C,s2,0.8,0.8
我对Python很陌生。
答案 0 :(得分:1)
让'raw'作为输入文件名,'output'作为输出文件名。
import csv
data = []
with open('raw', 'r') as f:
csvreader = csv.reader(f, delimiter=',')
for row in csvreader:
data.append(row)
with open('output', 'w') as f:
csvwriter = csv.writer(f)
csvwriter.writerow(['id', 'StageNo', 'Pow1', 'Pow2'])
for row in data[1:]:
csvwriter.writerow([row[0], 's1', row[1], row[2]])
csvwriter.writerow([row[0], 's2', row[3], row[4]])
的更多信息
答案 1 :(得分:0)
您可以使用csv模块csv.DictReader()
和csv.DictWriter()
import csv
with open('input.csv','r') as file:
reader = csv.DictReader(file)
with open('output.csv','w') as file_output:
writer = csv.DictWriter(file_output,fieldnames=['id','StageNo','Pow1','Pow2'])
writer.writeheader()
for line in reader:
line_split1 = {'id':line['id'],'StageNo':'s1','Pow1':line['Stage1Pow1'],'Pow2':line['Stage1Pow2']}
line_split2 = {'id':line['id'],'StageNo':'s2','Pow1':line['Stage2Pow1'],'Pow2':line['Stage2Pow2']}
writer.writerows([line_split1,line_split2])
输出:
id,StageNo,Pow1,Pow2
A,s1,1.0,1.5
A,s2,1.1,1.4
B,s1,0.9,1.2
B,s2,0.9,1.1
C,s1,1.0,1.0
C,s2,0.8,0.8