[英]Convert wide format csv to long format csv using python
I have some trouble to convert my csv data from a wide table format csv to a long format csv in python. 在python中将我的csv数据从宽表格式csv转换为长格式csv时遇到了一些麻烦。 At the moment it looks like this: 现在看起来像这样:
Time Temp1 Temp2 Temp3 Temp4 Temp5
00 21 32 33 21 23
10 34 23 12 08 23
20 12 54 33 54 55
Now I like to transform this data into a long data format. 现在,我想将这些数据转换为长数据格式。 Something like this: 像这样:
00 temp1 21
00 temp2 32
00 temp3 33
00 temp4 21
00 temp5 23
10 temp1 34
10 temp2 23
10 temp3 12
10 temp4 08
10 temp5 23
20 temp1 12
20 temp2 54
.
.
.
Any help on how to attack such a problem in python would be really helpful. 任何有关如何在python中解决此类问题的帮助都将非常有帮助。
You can use the csv module but the logic is the same. 您可以使用csv模块,但逻辑相同。
with open("in.csv") as f,open("out.csv","w") as out:
headers = next(f).split()[1:] # keep headers/Time Temp1 Temp2 Temp3 Temp4 Temp5
for row in f:
row = row.split()
time = row[0]
data = zip(headers, row[1:]) # match correct temp to row item
for a, b in data:
out.write("{} {} {}\n".format(time,a.lower(),b))
print("{} {} {}".format(time,a.lower(),b))
00 temp1 21
00 temp2 32
00 temp3 33
00 temp4 21
00 temp5 23
10 temp1 34
10 temp2 23
10 temp3 12
10 temp4 08
10 temp5 23
20 temp1 12
20 temp2 54
20 temp3 33
20 temp4 54
20 temp5 55
out.csv: out.csv:
00 temp1 21
00 temp2 32
00 temp3 33
00 temp4 21
00 temp5 23
10 temp1 34
10 temp2 23
10 temp3 12
10 temp4 08
10 temp5 23
20 temp1 12
20 temp2 54
20 temp3 33
20 temp4 54
20 temp5 55
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.