使用python将宽格式csv转换为长格式csv

时间:2015-01-13 20:45:05

标签: python csv

将csv数据从宽表格式csv转换为python中的长格式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中攻击此类问题的帮助都会非常有用。

2 个答案:

答案 0 :(得分: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 :(得分:1)

尝试使用pandas Dataframe存储csv文件的数据。它提供了一个内置函数pandas.melt,它对您的问题很有用。

以下是文档的link

相关问题