2015-01-13 61 views
1

我有一些麻烦将我的csv数据从宽表格式csv转换为python中的长格式csv。目前看起来像这样:使用python将宽格式csv转换为长格式csv

Time Temp1 Temp2 Temp3 Temp4 Temp5 
00 21  32 33 21 23 
10 34  23 12 08 23 
20 12  54 33 54 55 

现在我想将这些数据转换为长数据格式。这样的事情:

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 
. 
. 
. 

任何关于如何在python中攻击这样的问题的帮助将是非常有用的。

+0

什么时间? –

+0

时间列表示以秒为单位的经过时间,并且温度1,温度2,温度3,温度4,温度5列表示在该时刻来自不同传感器的温度。 –

回答

1

您可以使用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:

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 
+1

如果文件真的被可变长度的空格分隔,这可能比'csv'更自然。 – DSM

1

尝试使用大熊猫数据帧用于存储csv文件的数据。它提供了一个内置函数pandas.melt,这对你的问题很有用。

以下是文档中的link